I am trying to replace a string where a specific condition is true in the same line
I have a file with some lines. I to replace a word (word1) with another (word2) in every line that starts with another word (word3)
For example:
foo moo see
kaa haa qee
foo dee see
uuu ooo rrr
foo dee laa
I want to replace the word "see" with "raa" in every line which begins with "foo". So doing that will result in the lines being like:
foo moo raa
kaa haa qee
foo dee raa
uuu ooo rrr
foo dee laa
I was told that I can use sed to do that but I didn't figure out how to do that.
Please help! (with sed only)
This is very basic sed:
$ sed '/^foo/s/see/raa/g' file
foo moo raa
kaa haa qee
foo dee raa
uuu ooo rrr
foo dee laa
sed 's/something/replacement/g' replaces something strings with replacement. The g indicates that it is to be done every time it can./^foo/ makes it just take into consideration the lines starting with foo.-i: sed -i.bak '/^foo/s/see/raa/g' file. file.bak will contain the previous file.How to use variables instead of foo, see, raa ? – Khaleal
Like this and with double quotes:
$ d="foo"
$ e="see"
$ sed "/^$d/s/$e/raa/g" file
foo moo raa
kaa haa qee
foo dee raa
uuu ooo rrr
foo dee laa
and so on.
I know its asked for sed, but posting an awk for other to read, if they like.
awk '/^foo/ {sub(/see/,"raa")}1' file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With