2

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)

0

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How to use variables instead of foo, see, raa ?
See my updated answer, @Khaleal If it's done, remember you can accept the answer.
just be carefull with special char in word like . * \ & ? + that have sed meaning in s. Your sample does not show any of them but this is maybe not the case in all your file
4

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

awk '/^foo/ {sub(/see/,"raa")}1' file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.