LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   need sed help - how to replace all instances of X except those on lines with Y? (https://www.linuxquestions.org/questions/programming-9/need-sed-help-how-to-replace-all-instances-of-x-except-those-on-lines-with-y-630609/)

BrianK 03-25-2008 05:14 PM

need sed help - how to replace all instances of X except those on lines with Y?
 
say I have a file:

Code:

foo bar
gah foo bar
foo foo
bar gah
foo gah

... and I want to replace all instances of "foo" with "oof" except those on lines that also have "gah". So, I would want the output to look like:

Code:

oof bar
gah foo bar
oof oof
bar gah
foo gah

Is this even possible?

cmnorton 03-25-2008 06:12 PM

One sed Example
 
If I correctly understood what you wrote, this seems to work:

#!/bin/sed

/\(.*\)\(gah\)\(.*$\)/!s/foo/oof/g

I wanted to find all lines without gah, and then do a simple substitution on those lines. You could do this with something more complicated, but then you'd be getting into parts of matches, which gets more complicat

BrianK 03-25-2008 06:23 PM

Quote:

Originally Posted by cmnorton (Post 3100345)
If I correctly understood what you wrote, this seems to work:

#!/bin/sed

/\(.*\)\(gah\)\(.*$\)/!s/foo/oof/g

I wanted to find all lines without gah, and then do a simple substitution on those lines. You could do this with something more complicated, but then you'd be getting into parts of matches, which gets more complicat

perfect! Thanks! That would have taken a really long time to figure out. ;)

osor 03-25-2008 06:39 PM

Except it doesn’t have to be so complicated:
Code:

sed -e '/gah/!s/foo/oof/g'

BrianK 03-25-2008 06:49 PM

Quote:

Originally Posted by osor (Post 3100370)
Except it doesn’t have to be so complicated:
Code:

sed -e '/gah/!s/foo/oof/g'

well that's even prettier. Thanks.


All times are GMT -5. The time now is 04:28 PM.