Re: [OT] sed command to add line after matching lines

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Dan Track wrote:
Hi

I appreciate this is off-topic but I would be grateful for some help
on this. Basically,I want to add a few lines after matching a couple
of lines in a file using sed, can someone please tell me how to do
this.

Lines to match

server 10.33.45.3
server ldap.example.com
server orion

I want to comment these lines so they become:

# server 10.33.45.3
# server ldap.example.com
# server orion

Then append these lines after the commented lines

server fire.example.com
server earth.example.com
server space.example.com


So I should end up with:

# server 10.33.45.3
# server ldap.example.com
# server orion

server fire.example.com
server earth.example.com
server space.example.com

Please bear in mind there is a lot of other text in this file not just
the above and all the other text should remain untouched.

I don't think you can match only when you hit three lines in succession because sed is supposed to operate on one line at a time, which is what I think you are asking for. If all you want to do is comment out each of those lines and add some new ones, you could try the quick and dirty way:

$ cat testfile
server 10.33.45.3
server ldap.example.com
server orion
$ cat testfile | sed -e 's/^server 10.33.45.3$/# server 10.33.45.3/g' -e 's/^server ldap.example.com$/# server ldap.example.com/g' -e 's/^server orion$/# server orion\n\nserver fire.example.com\nserver earth.example.com\nserver space.example.com/g'
# server 10.33.45.3
# server ldap.example.com
# server orion

server fire.example.com
server earth.example.com
server space.example.com

But if your lines are out of order, then you might end up with something like this:

$ cat testfile2
server 10.33.45.3
server orion
server ldap.example.com
$ cat testfile2 | sed -e 's/^server 10.33.45.3$/# server 10.33.45.3/g' -e 's/^server ldap.example.com$/# server ldap.example.com/g' -e 's/^server orion$/# server orion\n\nserver fire.example.com\nserver earth.example.com\nserver space.example.com/g'
# server 10.33.45.3
# server orion

server fire.example.com
server earth.example.com
server space.example.com
# server ldap.example.com

--
fedora-list mailing list
fedora-list@xxxxxxxxxx
To unsubscribe: https://www.redhat.com/mailman/listinfo/fedora-list
Guidelines: http://fedoraproject.org/wiki/Communicate/MailingListGuidelines

[Index of Archives]     [Current Fedora Users]     [Fedora Desktop]     [Fedora SELinux]     [Yosemite News]     [Yosemite Photos]     [KDE Users]     [Fedora Tools]     [Fedora Docs]

  Powered by Linux