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

bash, replace, sed, text

Solution

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

Problem

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).

Original source

Related problems