Linux AWK——比较两个不同文件中两个变量的值
我有两个文本文件A.txt和B.txt。A.txt的每一行 A.txt B.txt 我要找的是这样的东西:Linux AWK——比较两个不同文件中两个变量的值,linux,bash,awk,text-processing,Linux,Bash,Awk,Text Processing,我有两个文本文件A.txt和B.txt。A.txt的每一行 A.txt B.txt 我要找的是这样的东西: 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; cat f1 1 4 9 16 cat f2 2 4 10 8 3 9 20
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;
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
任何这样做的awk???使用如下awk:
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;
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
看看与嵌套for循环相比,基于awk的解决方案有多简单。这样的解决方案怎么样 我在理解你的问题时遇到了一些困难,但也许这会给你一些建议
#!/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
注意,- 这是一件又快又脏的事情,还有改进的余地。但我认为它会成功的
#!/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