如何在shell脚本中优化sed搜索和替换

时间:2016-09-09 09:06:56

标签: bash shell

我必须最多启动sed三次,因为单词startpilot每行可以出现多次。我认为这个脚本可以编写得更好,也许任何人都可以帮助我优化它。

grep -rl "startpilot" ./* -R | xargs sed -i '' "s/startpilot/${PWD##*/}/"

#! /bin/bash

DIR="$1"

if [ $# -ne 1 ]
then
    echo "Usage: $0 {new extension key}"
    exit 1
fi

if [ -d "$DIR" ]
then
    echo "Directory/extension '$DIR' exists already!"
else
    git clone https://github.com/misterboe/startpilot.git $DIR --depth=1
    echo "$DIR created."
    cd $DIR && rm -rf .git && grep -rl "startpilot" ./* -R | xargs sed -i '' "s/startpilot/${PWD##*/}/" && grep -rl "startpilot" ./* -R | xargs sed -i '' "s/startpilot/${PWD##*/}/" && grep -rl "startpilot" ./* -R | xargs sed -i '' "s/startpilot/${PWD##*/}/" && grep -rl "Startpilot" ./* -R | xargs sed -i '' "s/Startpilot/${PWD##*/}/"
    cd Resources/Public/ && bower install
    echo "Your extension is now in $DIR."
fi

1 个答案:

答案 0 :(得分:2)

如果要替换所有出现的" startpilot"使用${PWD##*/},只需将g(全局)修饰符添加到sed命令:

sed -i '' "s/startpilot/${PWD##*/}/g"
                                   ^ here

现在它将取代所有这些,而不是替换该行上的第一个匹配项。

相关问题