Nate
Nate

Reputation: 28434

Linux bash script: how to search on a column but return full row?

I have a tab-delimited file with data like this:

col1    col2    col3

I wrote a bash script that allows the file to be searched using this code:

echo -en "Search term: "
read search

data=`cat data.data | egrep -i "$search"`

This works great for searching the entire file, but I'm now wanting to search only on a specific column (which the user can choose).

I am aware of the cut command and can search on a column using this:

cat data.data | cut -f$col | egrep -i "$search"

But then only that column is outputted, so if I use this method then I somehow need to get the rest of the row back.

How can I search on a column in the file, but return the full rows for the results?

Upvotes: 3

Views: 2316

Answers (2)

Tom Fenech
Tom Fenech

Reputation: 74695

You can pass two variables to awk: the column number and the search term.

awk -vcol="$col" -vsearch="$search" '$col ~ search' data.data

If the value of $col is 2, then $2 in awk will correspond to the second column. The ~ operator is used to do a regular expression pattern match. The line will be printed if the column matches the regular expression.

Testing it out:

$ cat data.data
col1    col2    col3
$ col=2
$ search=l2
$ awk -vcol="$col" -vsearch="$search" '$col ~ search' data.data
col1    col2    col3
$ search=l3
$ awk -vcol="$col" -vsearch="$search" '$col ~ search' data.data
# no output

If you want to do case-insensitive pattern matching, you have two options: convert everything to upper or lower case (tolower($col) ~ tolower(search)), or if you are using GNU awk, set the IGNORECASE variable:

$ search=L2
$ awk -vIGNORECASE=1 -vcol="$col" -vsearch="$search" '$col ~ search' data.data
col1    col2    col3

Upvotes: 3

P.P
P.P

Reputation: 121417

awk is easier for this:

data=$(awk -v col=$col -v term="$term" 'toupper($col)==toupper(term)' file)

col - column number
term - search term

You could also pass field separator with -F if needed.

Upvotes: 1

Related Questions