Given a hostname in format of aaa0.bbb.ccc
, I want to extract the first substring before .
, that is, aaa0
in this case. I use following awk script to do so,
echo aaa0.bbb.ccc | awk '{if (match($0, /\./)) {print substr($0, 0, RSTART - 1)}}'
While the script running on one machine A
produces aaa0
, running on machine B
produces only aaa
, without 0
in the end. Both machine runs Ubuntu/Linaro
, but A
runs newer version of awk(gawk with version 3.1.8 while B
with older awk (mawk with version 1.2)
I am asking in general, how to write a compatible awk script that performs the same functionality ...
substr(str, start, l) This function returns the substring of string str, starting at index start of length l. If length is omitted, the suffix of str starting at index start is returned.
NF is a predefined variable whose value is the number of fields in the current record. awk automatically updates the value of NF each time it reads a record. No matter how many fields there are, the last field in a record can be represented by $NF . So, $NF is the same as $7 , which is ' example.
You just want to set the field separator as .
using the -F
option and print the first field:
$ echo aaa0.bbb.ccc | awk -F'.' '{print $1}' aaa0
Same thing but using cut:
$ echo aaa0.bbb.ccc | cut -d'.' -f1 aaa0
Or with sed
:
$ echo aaa0.bbb.ccc | sed 's/[.].*//' aaa0
Even grep
:
$ echo aaa0.bbb.ccc | grep -o '^[^.]*' aaa0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With