append string after pattern match in solaris sed

897 views Asked by At

I have a file which contains the below

hosts:      files
ipnodes:    files
networks:   files
protocols:  files
rpc:        files
ethers:     files
netmasks:   files

I need to append "dns" at the end of only this two lines

hosts:      files dns
ipnodes:    files dns

Solaris servers, having very limited options in sed sed -i is not available looking for a workaround

2

There are 2 answers

3
gregory On

sed without any fancy settings or in place updates would work:

sed 's/.*/& dns/' file

If you need to make this edit to ONLY lines beginning with lines beginning with hosts and ipnodes, then add a filter to the command:

sed -e '/^hosts/ s/.*/& dns/' -e  '/^ipnodes/ s/.*/& dns/' file

Note: I am assuming you'll redirect output to a new file, and replace it with the old.

3
hek2mgl On

I'm surprised how minimal the Solaris sed really is. I would say use awk in that case but that seems broken as well. My recommendation is to not shell script on Solaris at all. Stop using Solaris and replace it by a reasonable OS if you want to work with shell scripting. Otherwise use a programming language like Python for scripting.


Former Answer:

The command should look like this:

sed 's/^\(hosts\|ipnodes\).*/& dns/' file

On Solaris sed the argument to -i is mandatory (unlike GNU sed)

sed -i '.backup' 's/^\(hosts\|ipnodes\).*/& dns/' file

That will create a file file.backup. Check man sed!