How to print out a specific field in AWK?

12,377

Solution 1

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.

Solution 2

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

Solution 3

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 )}'
Share:
12,377
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    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.