Search in a given column of a file with awk

From BITS wiki
Jump to: navigation, search


Although grep can easily return all lines containing a given text, it does not restrict its search to a particular region of the lines. When dealing with tabular files, it is often nice to look in a particular column and for a particular value that may be stored in a variable. Here is a nice way to achieve it.

Handicon.png You can also download the perl script csvgrep that offers more flexibility here.

search for text from a bash variable value in a file when present in a given column

# to use a shell variable use double quotes for awk and escape the awk variables with '\'
# bash does not expand $2 that belongs to awk 
# but does expands '$find_me' into its value
 
# define search string with a variable
find_me="blah"
 
# using '-F@' restores field separators to standard
# if the separator is different (eg ':') use instead awk -F ":"
 
# look in second column
awk -F@ "{if (\$2 ~ /$find_me/ ) { print \$0; } }" <input_file>
 
# which gets expanded by bash into
awk -F@ {if ($2 ~ /blah/ ) { print $0; } } <input_file>

Handicon.png Have a look to the wonder of AWK here