1

I have two text files A.txt and B.txt. Each line of A.txt A.txt

100
222
398

B.txt

1  2  103  2 
4  5  1026 74
7  8  209  55
10 11 122  78

What I am looking for is an awk command for doing this:

for each line of A 
    search B;
    if (the value of third column in a line of B - the value of the variable in A > 10)
        print that line of B;

2 Answers 2

1

The following script should solve your problem:

#!/bin/bash
A="$HOME/a.txt"
B="$HOME/b.txt"

cat $A | while read a; do
    cat $B | while read b; do
        b3=$(echo $b | awk ' { print $3 }')
        c=$(($b3 - $a))
        if (( $c > 10 )); then
            echo $b
        fi
    done
done

Don't forget to make it executable using the following command:

chmod +x script_name
2
  • It seems that your code only compares the variables with the same line number. What I need is to search whole B.txt and if the condition is true print that line of B.
    – user208434
    Oct 27, 2013 at 20:20
  • @user208434 Ah, that's more simple. Sorry, I didn't understood well your request. Oct 27, 2013 at 20:54
0

Here's another approach:

while read i; do awk -v i="$i" '$3-i>10' file2; done < file1

Explanation:

  • while read i; do ... ; done < file1 : This iterates through file one, saving the value it finds there (the entire line) as $i.
  • awk -v i=$i '$3-i>10' file2 : This goes through file2 and prints each line where the third field is less than the current value of $i. The trick is passing the variable to the awk script with the -v var_name=value option.

Note that this (and Radu's) answer, will print each line that matches for each variable. The result will be many duplicated lines, to remove them use sort:

while read i; do awk -v i="$i" '$3-i>10' file2; done < file1 | sort -u

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .