1

I would like to add a word into a file using a bash script. Specifically, I want a line in /etc/nsswitch.conf to go from

hosts:          files mdns4_minimal [NOTFOUND=return] dns myhostname

to

hosts:          files wins dns mdns4_minimal [NOTFOUND=return] dns myhostname

I have been trying with sed, but had no luck. I can't figure out how to search for a word and replace it or insert a word in that file.

  • try sed 's/files mdns4_minimal/files wins dns mdns4_minimal/g' – cmak.fr Sep 13 '19 at 9:01
  • What exactly do you want to search for and replace? If you want to just insert text after a specific field, e.g. files, awk might be a better option. – user3140225 Sep 13 '19 at 9:02
2

Capture the parts you don't want to change.

sed 's/^\(hosts:  *files\) \(mdns4_minimal\)/\1 wins dns \2/' input.file
  • \(...\) creates a capture group, while \1 references the first capture group, \2 the second one, etc.
  • ^ matches at the beginning of a line.
  • * means "the previous thing repeated zero or more times". I was too lazy to count the spaces.
  • add the option -i if you want to make the changes in place of the file, to create also a backup copy of the original file add -i.bak or -i.default.
  • I added the -i in order to add the filename; sed -i 's/^(hosts: *files) (mdns4_minimal)/\1 wins dns \2/' /etc/nsswitch.conf – eekfonky Sep 13 '19 at 9:22
  • @eekfonky, the option -i has different meaning. I've updated the answer. – pa4080 Sep 16 '19 at 5:51
  • @pa4080 thank you – eekfonky Sep 16 '19 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.