LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   sed, negate and variable (https://www.linuxquestions.org/questions/programming-9/sed-negate-and-variable-435382/)

muha 04-15-2006 07:54 AM

sed, negate and variable
 
Hey!
I'm trying to use sed to search through a text, and replace a variable containing spaces with 'bar'.
But i don't want to replace on lines containing 'foo'.
The reason i want to use a variable is that the sed-command is in a for-loop, so it get's a different variable each loop.

It works when i want to replace on lines with foo:
Code:

$ echo ${test}
test1 test2
$ echo ${test// /\\ }
test1\ test2
$ cat file
test1
test2
replace this test1 test2
don't replace when foo test1 test2
$ sed "/foo/s/${test// /\\ }/bar/g" file
test1
test2
replace this test1 test2
don't replace when foo bar

But when i want to negate lines, bash freaks out.
Code:

$ sed "/foo/!s/${test// /\\ }/bar/g" file
bash: !s/${test//: event not found

Also, this works of course:
Code:

$ sed '/foo/!s/test1\ test2/bar/g' file
test1
test2
replace this bar
don't replace when foo test1 test2

But i have to use double quotes for sed to understand my variable.
Otherwise i get:
Code:

$ sed '/foo/s/${test// /\\ }/bar/g' file
sed: -e expression #1, char 17: unknown option to `s'

So, can i negate the regular expression foo without using !
Or can i use sed-branching to test if the regexp foo is not on a line?
Or does anyone have a good hint on how to achieve this? Thanks!

jschiwal 04-15-2006 08:38 AM

Quote:

$ sed "/foo/!s/${test// /\\ }/bar/g" file
When in double quotes, the exclamation point is still a special character which replays a previous command.

You need the sed command in single quotes. You can fragment it so parts that need shell expansion are in double quotes.
sed '/foo/!s/'"${test// /\\ }"'/bar/g' file

muha 04-16-2006 09:02 AM

Ok, it works! I thought i had tried every possible combination of backticks, double/single quotes. Apperently not :D
Thanks heaps jschiwal!


All times are GMT -5. The time now is 11:51 AM.