1

I want to append .com at the end of line for every line matching the pattern in /etc/hosts file.

Sample file content:

127.0.0.1   localhost
1.2.3.4 hostname1 hostname1.xyz hostname1.xyz.  
1.2.3.5 hostname2 hostname2.xyz hostname2.xyz.  
1.2.3.6 hostname3 hostname3.xyz hostname3.xyz.  

I want it to be like below:

127.0.0.1   localhost localhost.com
1.2.3.4 hostname1 hostname1.xyz hostname1.xyz. hostname1.xyz.com  
1.2.3.5 hostname2 hostname2.xyz hostname2.xyz. hostname2.xyz.com  
1.2.3.6 hostname3 hostname3.xyz hostname3.xyz. hostname3.xyz.com

Any sed or awk command to achieve this effect?

4
  • So all your lines are in /etc/hosts?
    – cuonglm
    Jun 1, 2016 at 8:32
  • yes, they are in /etc/hosts file only. Jun 1, 2016 at 8:35
  • 1
    So awk '$0 = $0 " " $NF "com"' <file should do the trick.
    – cuonglm
    Jun 1, 2016 at 8:42
  • @cuonglm This works!! Thanks. Just for the sake of /etc/hosts consistency which also has "127.0.0.1 localhost" entry on first line, this added just "com" at the end of line. It should have been nice if it was localhost.com not localhostcom. Note: mind the DOT here. Jun 1, 2016 at 8:56

2 Answers 2

2

With awk:

$ awk '$0 = $0 " " $NF ($NF ~ /\.$/ ? "" : ".") "com"' <file
127.0.0.1   localhost localhost.com
1.2.3.4 hostname1 hostname1.xyz hostname1.xyz. hostname1.xyz.com
1.2.3.5 hostname2 hostname2.xyz hostname2.xyz. hostname2.xyz.com
1.2.3.6 hostname3 hostname3.xyz hostname3.xyz. hostname3.xyz.com
1
1

Solution using Perl, does inplace editing

perl -i -pe 's/(\s\S+?)(\.?)\s*$/$1$2$1.com\n/' /etc/hosts
  • \s match a white-space character
  • \S+? non-greedy match 1 or more non-white-space characters
  • \.? greedy match 0 or 1 times the . character (to take care of possible extra . at end of line)
  • \s*$ greedy match any white-space characters at end of line
  • $1$2 retain the last column, excluding end of line white-space characters
  • $1.com\n add .com and newline character

change -i to -i.bkp to have a backup (/etc/hosts.bkp) of original file

Note: this regular expression won't work with sed as BRE/ERE doesn't support non-greedy matching

3
  • I moved to perl from awk as escaping the quotes, double quotes, $ etc. was giving me hard time. I am trying to execute this perl command using ssh on remote machine from a python program. What should be the way to escape all needed ones? Jun 4, 2016 at 10:01
  • what's your current line of code? and you could as well write this code in python to save all the trouble of calling external command
    – Sundeep
    Jun 4, 2016 at 10:30
  • program pseudo code goes like: <some python code> funcSshRemote(perl_cmd, remote_host) <some python code> Jun 4, 2016 at 18:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .