Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash replace string where specific condition is true

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)

like image 523
Khaleal Avatar asked Apr 19 '26 10:04

Khaleal


2 Answers

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

Explanation

  • sed 's/something/replacement/g' replaces something strings with replacement. The g indicates that it is to be done every time it can.
  • Adding /^foo/ makes it just take into consideration the lines starting with foo.
  • If you want the file to be edited in place, that is, to have the file content updated with the substitution, add -i: sed -i.bak '/^foo/s/see/raa/g' file. file.bak will contain the previous file.

Update

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.

like image 60
fedorqui 'SO stop harming' Avatar answered Apr 21 '26 13:04

fedorqui 'SO stop harming'


I know its asked for sed, but posting an awk for other to read, if they like.

awk '/^foo/ {sub(/see/,"raa")}1' file
like image 30
Jotne Avatar answered Apr 21 '26 14:04

Jotne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!