88

I have a situation where i want to replace a particular string in many files

Replace a string AAA with another string BBB but there are lot of strings starting with AAA or ending in AAA ,and i want to replace only one on line 34 and keep others intact.

Is it possible to specify by line number,on all files this string is exactly on 34th line.

2 Answers 2

148

You can specify line number in sed or NR (number of record) in awk.

awk 'NR==34 { sub("AAA", "BBB") }'

or use FNR (file number record) if you want to specify more than one file on the command line.

awk 'FNR==34 { sub("AAA", "BBB") }'

or

sed '34s/AAA/BBB/'

to do in-place replacement with sed

sed -i '34s/AAA/BBB/' file_name
3
  • @VanagaS Thanks, what if I need to replace all the matches I find starting from line 34 and afterwards till EOF? possible entries within lines 1 and 34 shouldn't be touched. thanks Feb 3, 2020 at 16:30
  • @ramruma can you give hints? Feb 3, 2020 at 16:31
  • @jacquelyn.marquardt you can do something like sed 34,\$s/aaa/bbb/ filename you can find all options using the man pages under the addresses section: man sed
    – Kevin P.
    Feb 15, 2020 at 2:52
-3

lets suppose that you want to replace the third line in the file_record:

sed -i "s/`head -3 file_record | tail -1 `/replaced/" file_record
2
  • use back quote before head and after -1 ... here it is not taking it
    – RAMAN
    Dec 19, 2017 at 8:22
  • 1
    This just isn't going to work. It needs some heavy-duty escaping. And what if the third line is duplicated elsewhere?
    – Sparhawk
    Dec 19, 2017 at 9:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .