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.

    4 Answers 4

    2

    One way:

    sed -e '4 { /test/s/abc/zz/g }' <file 
    0
      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

        2
        • 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 ?CommentedNov 23, 2017 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.
          – bllidn3dd
          CommentedNov 27, 2017 at 15:55
        -1

        you can use this

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

          You must log in to answer this question.

          Start asking to get answers

          Find the answer to your question by asking.

          Ask question

          Explore related questions

          See similar questions with these tags.