如何编写一个从file1到file2查询的匹配结果中不同列的file3?
我有file1.txt和file2.txt,其中包含以下结构
file1.txt
5511913332222
5511910000023
5511910000029
5511910000034
file2.txt,
5511910000029|BLOCKED|7|30/07/2021 02:19:43
5511910000034|AVAIL|7|30/07/2021 03:11:53
5511910000048|AVAIL|7|30/07/2021 04:10:25
5511910000073|BLOCKED|7|30/07/2021 07:20:33
我想编写一个file3.txt,其中一个文件2的第一和第二列,其中第一个列与file1.txt的第一列匹配。
file3.txt
5511910000029|BLOCKED
5511910000034|AVAIL
我尝试了一些尴尬的技巧,但我无法获得预期的结果。有人可以帮我吗?
awk'nr == fnr {a [$ 0]} nr> fnr&& {print}'file1 file2> file3
I have file1.txt and file2.txt with the following structure
File1.txt
5511913332222
5511910000023
5511910000029
5511910000034
File2.txt
5511910000029|BLOCKED|7|30/07/2021 02:19:43
5511910000034|AVAIL|7|30/07/2021 03:11:53
5511910000048|AVAIL|7|30/07/2021 04:10:25
5511910000073|BLOCKED|7|30/07/2021 07:20:33
I want to write a file3.txt with the 1st and 2nd columns of the file2 where the 1st column matched the 1st column of file1.txt.
File3.txt
5511910000029|BLOCKED
5511910000034|AVAIL
I have tried some tricks with awk but I couldn't get the expected result. Could anyone please help me?
awk 'NR==FNR{a[$0]}NR>FNR && $0 in a{print}' file1 file2 > file3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要将输出保存到file3.txt
... {打印$ 1,$ 2> “ file3.txt”} ...
To save output to File3.txt
... {print $1,$2 > "File3.txt"} ...
这意味着
在两个文件(
,输出(-j 1
)中的第一个字段上加入-O
)第一个和第二个字段(.1 ,
.2
)的第二个文件(2。
),使用bar作为字段定界符(-t'|'|'< /code>),然后对输入进行排序(
&lt;(stort)
)在第一个字段(-K1
)上,将bar作为定界符(再次 - t'|')。假设
file1.txt
和file2.txt
1)尚未排序; 2)可以分类; 3)不要像您在问题中显示的那样其他所有线空白。This means
join
on the first field in both files (-j 1
), outputting (-o
) the first and second fields (.1
,.2
) of the second file (2.
), using bar as a field delimiter (-t '|'
), and sorting the inputs (<(sort)
) on the first field (-k1
) with bar as a delimiter (`-t '|' again).This assumes that
file1.txt
andfile2.txt
1) aren't already sorted; 2) can be sorted; 3) don't have every other line blank, like you show in the question.由于 file1 中的行仅由数字组成,因此您可以使用
$ 0〜/^[:digit:]]+$/code>在将它们设置为键之前,
a
将输出字段分隔符设置为
|
,并将 file2 的字段分隔符也设置为|
<|
< em> file3 :
As the lines in file1 consist of only digits, you can verify that using
$0 ~ /^[[:digit:]]+$/
before setting them as a key ina
Set the output field separator to
|
and set the field separator of file2 also to|
The content of file3: