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 something like 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;

Any awk for doing that??

有帮助吗?

解决方案

How about something like this,

I had some troubles understanding your question, but maybe this will give you some pointers,

#!/bin/bash 

# Read intresting values from file2 into an array, 
for line in $(cat 2.txt | awk '{print $3}') 
do 
  arr+=($line)
done 

# Linecounter, 
linenr=0 

# Loop through every line in file 1, 
for val in $(cat 1.txt) 
do 
  # Increment linecounter, 
  ((linenr++)) 

  # Loop through every element in the array (containing values from 3 colum from file2) 
  for el in "${!arr[@]}"; 
  do
    # If that value - the value from file 1 is bigger than 10, print values
    if [[ $((${arr[$el]} - $val )) -gt 10 ]] 
    then
      sed -n "$(($el+1))p" 2.txt
      # echo "Value ${arr[$el]} (on line $(($el+1)) from 2.txt) - $val (on line $linenr from 1.txt) equals  $((${arr[$el]} - $val )) and is hence bigger than 10" 
    fi 
   done
done

Note,

  • This is a quick and dirty thing, there is room for improvements. But I think it'll do the job.

其他提示

Use awk like this:

cat f1
1
4
9
16

cat f2
2 4 10 8
3 9 20 8
5 1 15 8
7 0 30 8

awk 'FNR==NR{a[NR]=$1;next} $3-a[FNR] < 10' f1 f2
2 4 10 8
5 1 15 8

UPDATE: Based on OP's edited question:

awk 'FNR==NR{a[NR]=$1;next} {for (i in a) if ($3-a[i] > 10) print}'

and see how simple awk based solution is as compared to nested for loops.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top