Insert text in the middle of text file by sed
I found problem on how to add text line in the middle of the hosts file. Just like below
127.0.0.1 localhost
< i want to add text line here >
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
and want to use 'sed', My friend, Sajal Kayan (God of Scripting) introduce me on ref#1, actually I quite not understand that. So he get me 2 approaches.
#1
for each time i have to add text line, then do
>>> sed -i 's/127.0.0.1 localhost/127.0.0.1 localhost\n this is new line /' /etc/hosts
>>> sed -i 's/127.0.0.1 localhost/127.0.0.1 localhost\n this is new line 1/' /etc/hosts
>>> sed -i 's/127.0.0.1 localhost/127.0.0.1 localhost\n this is new line 2/' /etc/hosts
then we'll get
127.0.01 localhost
this is new line 2
this is new line 1
this is new line
this is good enough if we don't care about the order. But if you care , Sajal has 2nd approach
#2
>>> sed -i 's/127.0.0.1 localhost/127.0.0.1 localhost\n#dummyanchor/' /etc/hosts
>>> sed -i 's/#dummyanchor/this is line 1\n/#dummyanchor/' /etc/hosts
>>> sed -i 's/#dummyanchor/this is line 2\n/#dummyanchor/' /etc/hosts
note that #dummyanchor is a comment , does not affect our system.
ref#1 http://www-rohan.sdsu.edu/doc/sed.html
ref#2 http://www.linuxquestions.org/questions/linux-general-1/bash-programming-append-single-line-to-end-of-file-265534/
127.0.0.1 localhost
< i want to add text line here >
xxxxxxxxxxxxxxx
xxxxxxxxxxxxxxx
and want to use 'sed', My friend, Sajal Kayan (God of Scripting) introduce me on ref#1, actually I quite not understand that. So he get me 2 approaches.
#1
for each time i have to add text line, then do
>>> sed -i 's/127.0.0.1 localhost/127.0.0.1 localhost\n this is new line /' /etc/hosts
>>> sed -i 's/127.0.0.1 localhost/127.0.0.1 localhost\n this is new line 1/' /etc/hosts
>>> sed -i 's/127.0.0.1 localhost/127.0.0.1 localhost\n this is new line 2/' /etc/hosts
then we'll get
127.0.01 localhost
this is new line 2
this is new line 1
this is new line
this is good enough if we don't care about the order. But if you care , Sajal has 2nd approach
#2
>>> sed -i 's/127.0.0.1 localhost/127.0.0.1 localhost\n#dummyanchor/' /etc/hosts
>>> sed -i 's/#dummyanchor/this is line 1\n/#dummyanchor/' /etc/hosts
>>> sed -i 's/#dummyanchor/this is line 2\n/#dummyanchor/' /etc/hosts
note that #dummyanchor is a comment , does not affect our system.
ref#1 http://www-rohan.sdsu.edu/doc/sed.html
ref#2 http://www.linuxquestions.org/questions/linux-general-1/bash-programming-append-single-line-to-end-of-file-265534/
Comments
Post a Comment