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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
Method 2
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0