2

Suppose you have the following text file

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
10.0.5.213 c04c0.ac
10.0.5.213 c04c1.ac 
10.0.5.213 c04c2.ac 
10.0.5.213 c04c3.ac
10.0.5.213 c04c4.ac
10.0.5.213 c04c5.ac
10.0.5.213 c04c6.ac
10.0.5.213 c04c7.ac
10.0.5.213 c04c8.ac
....

How would you turn it into this?

127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
10.0.5.213 c04c0.ac c04c0
10.0.5.213 c04c1.ac c04c1
10.0.5.213 c04c2.ac c04c2
10.0.5.213 c04c3.ac c04c3 
10.0.5.213 c04c4.ac c04c4
10.0.5.213 c04c5.ac c04c5
10.0.5.213 c04c6.ac c04c6
10.0.5.213 c04c7.ac c04c7
10.0.5.213 c04c8.ac c04c8
....

I've managed to strip '.ac' from the hostnames. However I'm not sure why 'localhost' was not striped out by the regex. How can I modify the regular expression to only collect c04cx and append it to the end of the line?

cat /etc/hosts | awk '{print $2}'| sed -r 's/(c04c)([0-9]+)(.*)/\1\2/'

localhost
localhost
c04c0
c04c1
c04c2
c04c3
c04c4
c04c5
c04c6
c04c7
c04c8
2

If you want to modify only the lines with two columns, one with an IP address and one with a name ending in .ac, use a regex that matches this and only this. I recommend making sure your regex doesn't match comment lines.

sed -e 's/^\([\t ]*\)\([0-9a-fA-F.:][0-9a-fA-F.:]*\)\([\t ][\t ]*\)\([^\t ][^\t ]*\)\.ac\([\t ]*\)/\1\2\3\4.ac \4/'
             111111    222222222222222222222222222    33333333333    4444444444444        555555
  1. indentation
  2. IP address (IPv4 or IPv6)
  3. whitespace separating the columns
  4. hostname (without .ac)
  5. trailing space
1

You can do this easily in awk. The problem with your command is that you use both awk and sed. You are discarding most of the line with the awk.

The example below just matches the second column against a regex and prints the entire line, with the new data appended:

awk '{ if ( match($2, /(c04c[0-9]+)[.]ac/, arr) ) {
           print $0" "arr[1];
        } else {
           print;
     }' < /etc/hosts > newfile
0
sed 's/[[:blank:]]\(c04c[0-9]\{1,\}\).*/& \1/'

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.