algoProg algoProg - 1 month ago 6
Bash Question

Bash script sed

I am trying to use

sed
in bash script as follows:

#!/bin/bash
for i in `seq 1 10`;
do
j=$(($i-1))
OLD="-option_something something/string1_${j}.txt"
NEW="-option_somehting something/string1_${i}.txt"
sed -e "s/$OLD/$NEW/g" file_to_edit.txt
# sed -e "s/$OLD/$NEW/g" file_to_edit.txt > file_to_edit.txt.tmp && mv file_to_edit.txt.tmp file_to_edit.txt
done


But I keep getting following error:

sed: -e expression #1, char 71: unknown option to
s'`

I tried the commented line as well, but it does not work too.

It works fine on command line. I do not know what is the problem in script.

Any suggestions? Thanks.

Answer

You have a / in the value of OLD and NEW, which is the same character you're using as the delimiter in your sed expression. So the final expression ends up looking like:

sed -e "s/-option_something something/string1_${j}.txt/-option_somehting something/string1_${i}.txt/g"

Do you see all the / in there? Consider instead:

sed -e "s|$OLD|$NEW|g" file_to_edit.txt

You can use any character as the delimiter for sed's s command.

Comments