bschauer
bschauer

Reputation: 1008

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. 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

Upvotes: 0

Views: 53

Answers (1)

Tom Fenech
Tom Fenech

Reputation: 74595

If you want to replace all occurrences of "startpilot" with ${PWD##*/}, just add the g (global) modifier to the sed command:

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

Rather than replacing the first occurrence on the line, now it will replace all of them.

Upvotes: 2

Related Questions