1

I need to use sed to change a string in a file only on the 4th line if it contains a string called "test"

So basically What I got right now is:

sed '/test/ s/abc/zz/g' sample

This will basically look through the lines and see if it has test and than change the abc to zz if its in that line.

But how do I do it only for the 4th line.

I tried

 sed '/test/ 4s/abc/zz/g' sample

Adding the 4 infront of the s , but it doesnt work.

1

One way:

sed -e '4 {
  /test/s/abc/zz/g
}' <file
0

I am not sure, but would something like this work?

awk 'NR==4 {print $0}' filename.txt | grep 'test' | sed 's/abc/xyz/g'
-1

another way:

first find the line with that string "test":

LINE=$(grep "test" file -n | awk '{print $1}' | cut -d ':' -f1 | xargs)

then using that variable LINE do:

sed "s$LINEs/abc/zzz/g" file

  • 4
    The Q says 'use sed to change a string in a file only on the 4th line if it contains a string called "test"'. How does your post answer the question ? – don_crissti Nov 23 '17 at 14:02
  • It specyfically does find the string and defines the line and then base on that line it replaces the proper string with a text provided, however there's is no 4 in this answer, so it's even simpler. – bllidn3dnd Nov 27 '17 at 15:55
-1

you can use this

sed -i '4s/old_text/new_text/g' file_name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.