Tony Tony - 3 months ago 22
Bash Question

Bash Script and quoting SED

Below is my script where it will either accept a file input or stdin... but I can't get the escaping right! - I've tried single and double quotes etc...

while read line
do
sed 's/path\/12345/path\/12345 == useful name/g'
sed 's/path\/6789/path\/6789 == useful name - 2/g'
done < ${1:-/dev/stdin}

Answer

The sed commands read from standard input, as does the while read loop. This leads to confusion.

You probably want just this (no while read; do …; done loop around it — see the chat):

sed -e 's/path\/12345/path\/12345 == useful name/g' \
    -e 's/path\/6789/path\/6789 == useful name - 2/g' \
    "$@"

Inside a script, that will run the sed script on all the files specified on the command line, or standard input if no files are specified. That's what the "$@" means in this context.

$ cat > script.sh
sed -e 's/path\/12345/path\/12345 == useful name/g' \
    -e 's/path\/6789/path\/6789 == useful name - 2/g' \
    "$@"
$ bash script.sh
path/12345
path/12345 == useful name
path/23456
path/23456
path/6789
path/6789 == useful name - 2
android-path/67890-twirling
android-path/6789 == useful name - 20-twirling
$

I typed 4 lines:

path/12345
path/23456
path/6789
android-path/67890-twirling

The other lines are the output from the script. When I put the four typed lines into a file data, I got the output:

$ bash script.sh data
path/12345 == useful name
path/23456
path/6789 == useful name - 2
android-path/6789 == useful name - 20-twirling
$

That looks like what the script is supposed to do. We can debate whether the last line should be mapped, but the expressions used in the script do the mapping that's shown.

Comments