使用awk读取文件并搜索另一个文件 [英] Read file and search another file using awk

查看:496
本文介绍了使用awk读取文件并搜索另一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取每行都有数字的文件. 我需要搜索另一个满足这些编号和其他条件的文件.我正在尝试使用awk进行此操作,但是遇到了问题.

I am reading a file having numbers on each line. I need to search another file meeting conditions on those numbers and other conditions. I am trying to do this using awk, but face a problem.

文件a.txt:

1476
1477
1497

现在我需要在第12列打印具有这些数字的行,并在第3列打印具有0的行.

Now I need to print lines having these numbers at 12th column along with having 0 at 3rd column.

文件b.txt:

r 1.040496 2 1 ack 40 ------- 1 3.0 0.0 0 1165
r 1.040496 2 1 ack 40 ------- 1 3.0 0.0 0 1165
r 1.050528 2 1 ack 40 ------- 1 3.0 0.0 0 1165
r 1.050528 1 0 ack 40 ------- 1 3.0 0.0 0 1165
r 1.050528 1 0 ack 40 ------- 1 3.0 0.0 0 1476
r 1.06056 1 0 ack 40 ------- 1 3.0 0.0 0 1165
r 1.06056 0 1 tcp 1040 ------- 1 0.0 3.0 1 1203
r 1.06056 0 1 tcp 1040 ------- 1 0.0 3.0 1 1203
r 1.06056 0 1 tcp 1040 ------- 1 0.0 3.0 2 1477
r 1.061392 0 1 tcp 1040 ------- 1 0.0 3.0 2 1204
r 1.071392 0 1 tcp 1040 ------- 1 0.0 3.0 1 1497
r 1.071392 1 2 tcp 1040 ------- 1 0.0 3.0 1 1203

我的脚本:

while read LINE
do
    awk -F ' ' '($3 == 0) && ($12 == $LINE)' b.txt
done < a.txt

不返回任何内容.

推荐答案

尝试:

$ while read line; do awk -v x="$line" '($3 == 0) && ($12 == x)' b.txt; done < a.txt
r 1.06056 0 1 tcp 1040 ------- 1 0.0 3.0 2 1477
r 1.071392 0 1 tcp 1040 ------- 1 0.0 3.0 1 1497

在这里,我们使用-v选项将awk变量x赋值为shell变量$line的值.

Here, we use the -v option to assign awk variable x to have the value of shell variable $line.

我们不需要shell循环:

We don't need the shell loop:

$ awk 'FNR==NR{a[$1]; next} $3==0 && $12 in a' a.txt b.txt
r 1.06056 0 1 tcp 1040 ------- 1 0.0 3.0 2 1477
r 1.071392 0 1 tcp 1040 ------- 1 0.0 3.0 1 1497

在读取第一个文件a.txt时,我们为每行中的值创建一个键为关联数组a.

While reading the first file, a.txt, we create a key is associative array a for the value on each line.

在读取第二个文件b.txt时,如果$3==0和字段12 $12是关联数组a中的键,我们将打印该行.

When reading the second file, b.txt, we print the line if $3==0 and field 12, $12, is a key in associative array a.

如果我需要添加结果的第二列怎么办?"

$ awk 'FNR==NR{a[$1]; next} $3==0 && $12 in a {s+=$2; print} END{print "Sum=",s+0}' a.txt b.txt
r 1.06056 0 1 tcp 1040 ------- 1 0.0 3.0 2 1477
r 1.071392 0 1 tcp 1040 ------- 1 0.0 3.0 1 1497
Sum= 2.13195

这篇关于使用awk读取文件并搜索另一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆