I have this awk command:
echo www.host.com |awk -F. '{$1="";OFS="." ; print $0}' | sed 's/^.//'
which what it does is to get the domain from the hostname:
host.com
that command works on CentOS 7 (awk v 4.0.2), but it does not work on ubuntu 19.04 (awk 4.2.1) nor alpine (gawk 5.0.1), the output is:
host com
How could I fix that awk expression so it works in recent awk versions ?
4
Answers
For your provided samples could you please try following. This will try to match regex from very first
.
to till last of the line and then prints after first dot to till last of line.OP’s code fix: In case OP wants to use his/her own tried code then following may help. There are 2 points here: 1st- We need not to use any other command along with
awk
to processing. 2nd- We need to set values ofFS
andOFS
inBEGIN
section which you are doing in everyline.To get the domain, use:
Explained:
It also works if you have arbitrarily long fqdns:
And yeah, funny, your version really works with 4.0.2. And awk version 20121220.
Update:
Updated with some content checking features, see comments. Are there domains that go higher than three levels?:
You got 2 very good answers on awk but I believe this should be handled with
cut
because of simplicity it offers in getting all fields starting for a known position:Options used are:
-d.
: Set delimiter as.
-f2-
: Extract all the fields starting from position 2What you are observing was a bug in GNU awk which was fixed in release 4.2.1. The changlog states:
When reading the code in the OP, it states:
which, according to POSIX does the following:
-F.
: set the field separatorFS
to represent the <dot>-characterFS="."
$1=""
: redefine field 1 and rebuild record$0
usingOFS
. At this time,OFS
is set to be a single space. If the record$0
waswww.foo.com
it now reads_foo_com
(underscores represent spaces). Recompute the number of fields which are now only one as there is noFS
available anymore.OFS="."
: redefine the output field separatorOFS
to be the <dot>-character. This is where the bug happens. The Gnu awk knew that a rebuild needed to happend, but did this already with the newOFS
and not the oldOFS
.print $0':** print the record $0 which is now
_foo_com`.The minimal change to your program would be:
The clean change would be:
The perfect change would be to replace the
awk
andsed
by thecut
solution of AnubahuvaIf you have a variable with that name in there, you could use: