简体   繁体   English

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

[英]How to optimize sed search and replace in shell script

I must launch sed up to three times because the word startpilot can occur more than once per row. 我必须启动sed最多3次,因为单词startpilot可能在每行中出现多次。 I think this script could be written much better, perhaps anybody could help me to optimize that. 我认为这个脚本可以写得更好,也许有人可以帮助我优化它。

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

If you want to replace all occurrences of "startpilot" with ${PWD##*/} , just add the g (global) modifier to the sed command: 如果要用${PWD##*/}替换所有出现的“ startpilot”,只需将g (全局)修饰符添加到sed命令中:

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

Rather than replacing the first occurrence on the line, now it will replace all of them. 现在,它将替换所有这些,而不是替换该行上的第一个匹配项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM