I have a text file. The text file contains the below content.

ServerAdmin webmaster@localhost

I need to insert a text www.mydomain.com, after the ServerName. Is there any command to do this?


Using sed:

sed 's/^\(ServerName\)$/\1 www.mydomain.com/' file.txt

The captured group, \(ServerName\) is used in the replacement pattern as \1.

Editing the file in place, with backup, assuming the GNU, ssed, busybox or some BSD implementations of sed:

sed -i.bak 's/^\(ServerName\)$/\1 www.mydomain.com/' file.txt

The original file will be kept as file.bak and the modified file will be file.txt.bak.

Editing in place, without backup (GNU, ssed or busybox only):

sed -i 's/^\(ServerName\)$/\1 www.mydomain.com/' file.txt

(for BSDs, use sed -i '' 's/...).

Even shorter, without any captured group:

sed -i 's/^ServerName$/& www.mydomain.com/' file.txt

Here & will be replaced by the match.

sed --in-place 's/ServerName/& www.example.com/' /path/to/apache-vhost.conf

Using sed substitue command:

sed -i 's/ServerName/ServerName www.mydomain.com/' file.txt
  • after ServerName , no under ServerName (no new line) – بارپابابا Jun 20 '16 at 6:32
  • @Babyy Right! Misread the question! :P – coffeMug Jun 20 '16 at 6:34

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.