Using Bash How Do You Replace a Line with a String with a Forward Slash in a File by Its Line Number?

Problem scenario
How do you insert a string with forward slashes using a perl command like this?

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

This command would insert "Hello World" on the 15th line of the text file named foobar.txt.  Instead of "Hello World" you want something else inserted that happens to include forward slashes ("/").  You want to identify a line in a file by its line number.  You want this line to be overwritten with a string that includes, among other characters, a forward slash.  How do you do this?

Use "\" backslashes right before the forward slashes.  Here is an example to insert cfg_dir=/usr/local/someprog/etc/hadoop into foobar.txt (line 15 with full deletion of line 15's previous content):

perl -i -pe 's/.*/cfg_dir=\/usr\/local\/someprog\/etc\/hadoop/ if $.==15' foobar.txt

# For your reference:
# The "/" to the left of the "cfg_dir" is for the command itself.  
# The last "/" is for the perl command itself (not the input).

Leave a comment

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