Using Bash How Do You Replace a Line in a File by Its Line Number?

Problem scenario
On your Linux server you know one line in a file needs to be replaced.  You can identify the file by its line number.  You have a string or pattern you want to be inserted where this line is. How do you do this with Bash?

Solution
To replace all the content of line 15 of foobar.txt with "Hello World" run this command:

perl -i -pe 's/.*/Hello World/ if $.==15' foobar.txt

For something more advanced, you may want to inject a string with forward slashes.  Unix uses forward slashes in directory paths.  Perl does not parse these forward slashes like other alphanumeric symbols.  You have to use a back slash to have Perl place a forward slash in the manner described above.   This example below will replace whatever is on line 34 of /tmp/contint.txt with "/subdirectory/path/to/file" with no quotes.

perl -i -pe 's/.*/ \/subdirectory\/path\/to\/file/ if $.==2' blah

Leave a comment

Your email address will not be published. Required fields are marked *