Mattii
Mattii

Reputation: 109

How to filter rows by a variable bash

I need to filter row by a bash variable.

var=$(cat $1 | awk -F"\t" ' $1 == "foo1" { print $0 }')
echo $var

I'm trying this to replace the string "foo1" to a variable

column2=$(echo "foo1")
echo $column2
var=$(cat $1 | awk -v pres=$column2 -F"\t" ' $1 == $pres { print $0 }')
echo $var

In the parameter $1 i pass a file.txt that have the next text

foo2    AAAA    561214
foo3    AAAA    3
foo4    AAAA    10470670
foo5    AAAA    443507
foo1    AAAA    12473709
foo6    AAAA    1599707
foo8    AAAA    382820
foo7    BBBB    100000000000000
foo1    AAAA    12473709
foo1    AAAA    12473709
foo1    AAAA    12473709
foo1    AAAA    12473709
foo1    AAAA    12473709
foo1    AAAA    12473709
foo1    AAAA    12473709

I need to do this with a variable, because i need to loop for each distinct value of the first column.

EDIT

#

My question is different than bash-How do i use shell variable in a awk script because i need to do a conditional to filter rows of a table in a file. I can do that is posted in that link, but i don't know how to combine to do

var=$(cat $1 | awk -F"\t" ' $1 == "foo1" { print $0 }')

that is working but when i tried to insert the variable stop working.

Upvotes: 2

Views: 1285

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133458

Could you please try following.

column2="foo1"
var=$(awk -v pres="$column2" -F"\t" '$1==pres' "$1")

We need not to use cat here since awk could read Input_file itself.

2nd thing we need not to use print when we a condition is TRUE in code by default it will print that line(if no action given for that condition), so I removed it from code above.

Upvotes: 3

Romeo Ninov
Romeo Ninov

Reputation: 7225

You should use this construction:

column2="foo1"
var=$(cat $1 | awk -v pres=$column2 -F"\t" ' $1 == pres { print $0 }')

Variables in awk do not need the $ sign

Upvotes: 2

Related Questions