mamba4ever
mamba4ever

Reputation: 2672

How to search a file inside awk

I have 2 seperate files lostType.txt (shows the selected options), and lost.txt (shows the memory leaks) I am using dialog to create GUI. Using checkboxes, I am taking some number intervals from user to limit memory leaks that will be printed. What I have to do is, print the lines which memory leak is in selected size, and leak type is in lostType.txt

For example, this is lost.txt

LEAK SUMMARY
100 bytes definitely lost
0 bytes indirectly lost
0 bytes possibly lost
100 bytes still reachable
0 bytes suppressed

If user wants to see definetely lost, and indirect lost, lostType.txt has the following

definetely
indirectly

Suppose user selected to see leaks, where size is between 0 and 10 bytes OR 100 and 250 bytes. Now the output must be 100 bytes in 1 blocks definitely lost

What I did so far is the following,

for choice in $choices
do
    case $choice in
    1)
        #"Memory Leak <= 10 Byte"
        cat lost.txt | awk '{
            if ($1 <= 10 && $1 > 0 )
                print $1,$2" ==>",$3,$4     
            }'
        ;;

    2)
        #"10 Byte < Memory Leak <= 50 Byte"
        cat lost.txt | awk '{
            if ($1 <= 50 && $1 > 10 )
                print $1,$2" ==>",$3,$4     
            }'
        ;;

That is, depending on the selected size interval, I can print the values. However, I couldn't find a way to look for lostType ($3 for upper code). What I need to do is searching the file in awk like

cat lost.txt | awk '{
 if ($1 <= 50 && $1 > 10 AND IF $3 IS IN lostType.txt)
      print $1,$2" ==>",$3,$4   
 }'
;;

So my question is, how can I search a file inside awk?

Upvotes: 2

Views: 223

Answers (1)

Birei
Birei

Reputation: 36252

If I understand your question, the following awk command should work. You must provide both input files. Lost types are saved in a hash and compare the key with third field of the other one.

awk '
    FNR == NR { type[ $1 ] = 1; next } 
    $1 > 10 && $1 < 200 && type[ $3 ] { print $1,$2 " ==> " $3,$4 }
' lostType.txt lost.txt

But this way you would parse both for every case option. In my opinion should be a better solution to pass those variables to the awk command and run it only once.

case $choice in
1)
    limit_inf=0
    limit_sup=10
    break
    ;;
2)
    limit_inf=10
    limit_sup=50
    break
    ;;
...

And then:

awk -v li="$limit_inf" -v ls="$limit_sup" '
    FNR == NR { type[ $1 ] = 1; next } 
    $1 > li && $1 < ls && type[ $3 ] { print $1,$2 " ==> " $3,$4 }
' lostType.txt lost.txt

Upvotes: 1

Related Questions