Reputation: 189
I am trying to update the format in /etc/hosts
file.
sample
# more /etc/hosts
14.5.10.13 host1 host1.mydomain.com
14.5.10.14 host2 host2.mydomain.com
#
to
14.5.10.13 host1.mydomain.com host1
14.5.10.14 host2.mydomain.com host2
I tried this but didnt worked. Please suggest.
#sed 's/host{1,2} /host{1,2}.mydomain.com/' /etc/hosts
Upvotes: 1
Views: 155
Reputation: 113814
To swap the second and third fields in the file hosts but only if the second is host1
or host2
:
$ awk '$2~/^host[12]$/{a=$2; $2=$3; $3=a} 1' hosts
# more /etc/hosts
14.5.10.13 host1.mydomain.com host1
14.5.10.14 host2.mydomain.com host2
#
Here, $2~/^host[12]$/
selects only those lines whose second field matches one of the hosts of interest. For those lines, the second and third field are swapped. The final 1
is awk's cryptic shorthand for print-the-line.
To do something similar with sed:
$ sed -E '/ host[12] /{s/ (host[12]) ([[:alnum:].]*)/ \2 \1/}' hosts
# more /etc/hosts
14.5.10.13 host1.mydomain.com host1
14.5.10.14 host2.mydomain.com host2
#
Here, / host[12] /
selects only those lines that contain host1
or host2
surrounded by spaces. For those lines, host1
or host2
is swapped with the word that follows.
Upvotes: 1