Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract substring from a field with single awk in AIX

Tags:

grep

ksh

aix

awk

I have a file file with content like:

stringa    8.0.1.2     stringx
stringb    12.01.0.0    stringx

I have to get a substring from field 2 (first two values with the dot).
I am currently doing cat file | awk '{print $2}' | awk -F. '{print $1"."$2}' and getting the expected output:

8.0
12.01

The query is how to do this with single awk?
I have tried with match() but not seeing an option for a back reference. Any help would be appreciated.

like image 250
Vijesh Avatar asked Dec 07 '22 09:12

Vijesh


2 Answers

You can do something like this.

$ awk '{ split($2,str,"."); print str[1]"."str[2] }' file
8.0
12.01

Also, keep in mind that your cat is not needed. Simply give the file directly to awk.

like image 199
Andre Wildberg Avatar answered Feb 04 '23 02:02

Andre Wildberg


With GNU grep please try following command once.

grep -oP '^\S+\s+\K[[:digit:]]+\.[[:digit:]]+' Input_file

Explanation: Using GNU grep here. Using its -oP options to print matched part and enable PCRE with -P option here. In main program, matching from starting non-space characters followed by 1 or more spaces, then using \K option to forget that match. Then matching 1 or more digits occurrences followed by a dot; which is further followed by digits. If a match is found then it prints matched value.

like image 28
RavinderSingh13 Avatar answered Feb 04 '23 00:02

RavinderSingh13