How to replace an entire line in a text file by line number

user788171 picture user788171 · Jun 21, 2012 · Viewed 280.3k times · Source

I have a situation where I want a bash script to replace an entire line in a file. The line number is always the same, so that can be a hard-coded variable.

I'm not trying to replace some sub-string in that line, I just want to replace that line entirely with a new line.

Are there any bash methods for doing this (or something simple that can be thrown into a .sh script).

Answer

chepner picture chepner · Jun 21, 2012

Not the greatest, but this should work:

sed -i 'Ns/.*/replacement-line/' file.txt

where N should be replaced by your target line number. This replaces the line in the original file. To save the changed text in a different file, drop the -i option:

sed 'Ns/.*/replacement-line/' file.txt > new_file.txt