Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Awk to extract substring

Tags:

bash

awk

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 ...

like image 389
Richard Avatar asked Apr 16 '13 15:04

Richard


People also ask

How do I use awk substring?

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.

How do I use NF in awk?

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.


1 Answers

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 
like image 77
Chris Seymour Avatar answered Sep 21 '22 13:09

Chris Seymour