Search string at a particular position in a file

Hi,
i have a text file as :

abc    0       1     Pass
hjk     1       1     Pass
bhk    0        0     Fail
jjh     8          2    Pass
nkji    0         1     Pass

Now I want to check that if 1st column is jjh , then , store the value of 3rd string of that line in a variable. Hence, 2 will be stored.

This way I want value from any line depending upon its first column.

Assuming there won't be any duplicate

try

$ myvar=$(awk '$1=="jjh"{print $3}' file)
$ echo $myvar
2

Please use codetag

Hi Anamika08,

The following code may help too.

awk '
{
 if($1 == "jjh")
 {
 a[X]=$3
        for(i in a)
 print a
 }
} ' check_1st_coloumn
 

Output will be as follows.

2

NOTE: Where check_1st_coloumn is the file name.

Thanks,
R. Singh

Pass 1st field as an argument to awk.

$ Col1="jjh"
$ awk -v field1="$Col1" '$1 == field1 { print $3 }' test2

Hi Pravin,
thanks for ur reply. can u pls let me know what I have to write to do this in perl.

Do like this

$ perl -lane'/jjh/ && print "$F[2]"' file

to store result in bash variable

$ vars=$(perl -lane'/jjh/ && print "$F[2]"' file)
$ echo $vars
2
$ search="jjh"
$ perl -lane'/'$search'/ && print "$F[2]"' file
2

small update:

perl -lane 'print "$F[2]" if $F[0] =~ /jjh/ ' file

without condition it can match a pattern anywhere.

pure shell:

while [ "$A" != "jjh" ]; do read A B Var Rest || break; done < file; echo $Var
2

Perl with exact string comparison

search="jjh"
result=$(
perl -lane '$F[0] -eq "'"$search"'" && print "$F[2]"' file
)

All in shell

result=$(
while read A B C _; do [ "$A" = "jjh" ] && echo "$C"; done < file
)

NB this works with shells that run the while loop in a sub shell.