Reputation: 1817
I have a large text file that contains multiple columns of data. I'm trying to write a script that accepts a column number and keyword from the command line and searches for any hits before displaying the entire row of any matches.
I've been trying something along the lines of:
grep $fileName | awk '{if ($'$columnNumber' == '$searchTerm') print $0;}'
But this doesn't work at all. Am I on the right lines? Thanks for any help!
Upvotes: 4
Views: 4103
Reputation: 54392
The -v option can be used to pass shell variables to awk
command.
The following may be what you're looking for:
awk -v s=$SEARCH -v c=$COLUMN '$c == s { print $0 }' file.txt
EDIT:
I am always trying to write more elegant and tighter code. So here's what Dennis means:
awk -v s="$search" -v c="$column" '$c == s { print $0 }' file.txt
Upvotes: 2
Reputation: 488193
Looks reasonable enough. Try using set -x
to look at exactly what's being passed to awk
. You can also use different and/or more awk things, including getting rid of the separate grep:
awk -v colnum=$columnNumber -v require="$searchTerm"
"/$fileName/ { if (\$colnum == require) print }"
which works by setting awk variables (colnum
and require
, in this case) and then using the literal string $colnum
to get the desired field, and the variable require
to get the required-string.
Note that in all cases (with or without the grep
command), any regular expression meta-characters in $fileName
will be meta-y, e.g., this.that
will match the file named this.that
but also the file named thisXthat
.
Upvotes: 0