Easily search file and get line - little problem

hi,

file1.txt:

cell101 1 20.24.1.1 10
cell101 2 20.24.1.2 20
cell101 3 20.24.1.3 30
cell327 1 20.24.1.4 40
cell327 2 20.24.1.5 50
cell327 3 20.24.1.5 60
...

file2.txt:

cell101 1
cell327 1
cell327 3
...

according to values in file2.txt, the script should search lines and get values. what I want to see is:

IP is: 20.24.1.1 'sector 1 value 10'
IP is: 20.24.1.4 'sector 1 value 40'
IP is: 20.24.1.5 'sector 3 value 60'
...

and my code for this job is:

nawk 'NR==FNR{a[$1,$2]=$3;next} a[$1,$2]{print "IP is: "a[$1,$2]" '"'"'sector"$2" value "$4"'"'"'"}' /gc_sw/file1.txt /gc_sw/file2.txt

but I am seeing:

IP is: 20.24.1.1 'sector 1 value '
IP is: 20.24.1.4 'sector 1 value '
IP is: 20.24.1.5 'sector 3 value '
...

the values are not coming! :frowning: $4 doesnot working in my code?? how can i do it?

thanks

Try this,

awk 'NR==FNR{a[$1,$2]=$3;b[$1,$2]=$4;next} a[$1,$2]{print "IP is: " a[$1,$2] "'" '"'sector " $2 " value " b[$1,$2]"'"'"'"}' /gc_sw/file1.txt /gc_sw/file2.txt

OR

awk 'NR==FNR {a[$1$2]++;next} a[$1$2] { print "IP is: " $3  "'" '"'sector " $2 " value " $4 "'"'"'"}' /gc_sw/file2.txt /gc_sw/file1.txt
1 Like

pravin27, thanks dude. your second solution fails but first solution works well :slight_smile: thanks for your assist

Hi,

In my second solution I am reading file2 first and then file1. What error are you recieving ?

nawk 'NR==FNR {a[$1$2]++;next} a[$1$2] { print "IP is: " $3  "'" '"'sector " $2 " value " $4 "'"'"'"}' file2 file1
1 Like
while read line ; do grep "$line" file1.txt | read a a b c ; eval echo "IP is: $b 'sector $a value $c'" ; done<file2.txt
1 Like

oh pravin, you are right! it is ok now :slight_smile: working perfectly!! thanks dude

awk 'NR==FNR && NF{a[$1$2];next}$1$2 in a{printf "IP is: %s %csector %d  value  %d%c\n",$3,x,$2,$4,x}' x=039 file2 file1
1 Like
nawk '{
if(NR==FNR)
  _[$0]=1
else
  if(_[$1" "$2]==1)
    print "IP is:"$3 " sector "$2" value "$NF
}' file2 file1