user1191129
user1191129

Reputation: 33

How to print out a specific field in AWK?

A very simple question, which a found no answer to. How do I print out a specific field in awk?

awk '/word1/', will print out the whole sentence, when I need just a word1. Or I need a chain of patterns (word1 + word2) to be printed out only from a text.

Upvotes: 3

Views: 14694

Answers (4)

Vijay
Vijay

Reputation: 67211

i know you can do this with awk : an alternative would be :

sed -nr "s/.*(PATTERN_TO_MATCH).*/\1/p" file

or you can use grep -o

Upvotes: 1

Zsolt Botykai
Zsolt Botykai

Reputation: 51593

Well if the pattern is a single word (which you want to print and can't contaion FS (input field separator)) why not:

awk -v MYPATTERN="INSERT_YOUR_PATTERN" '$0 ~ MYPATTERN { print MYPATTERN }' INPUTFILE

If your pattern is a regex:

awk -v MYPATTERN="INSERT_YOUR_PATTERN" '$0 ~ MYPATTERN { print gensub(".*(" MYPATTERN ").*","\\1","1",$0) }' INPUTFILE

If your pattern must be checked in every single field:

awk -v MYPATTERN="INSERT_YOUR_PATTERN" '$0 ~ MYPATTERN { 
    for (i=1;i<=NF;i++) {
        if ($i ~ MYPATTERN) { print "Field " i " in " NR " row matches: " MYPATTERN }
    }
}' INPUTFILE

Modify any of the above to your taste.

Upvotes: 4

William Pursell
William Pursell

Reputation: 212218

The fields in awk are represented by $1, $2, etc:

$ echo this is a string | awk '{ print $2 }'
is

$0 is the whole line, $1 is the first field, $2 is the next field ( or blank ), $NF is the last field, $( NF - 1 ) is the 2nd to last field, etc.

EDIT (in response to comment).

You could try:

awk '/crazy/{ print substr( $0, match( $0, "crazy" ), RLENGTH )}'

Upvotes: 2

Dr G
Dr G

Reputation: 4017

Something like this perhaps:

awk '{split("bla1 bla2 bla3",a," "); print a[1], a[2], a[3]}'

Upvotes: 0

Related Questions