gpt4 book ai didi

linux - 从子文件中的母文件中搜索一个数字,并将子文件中的完整行追加到母文件中

转载 作者:太空宇宙 更新时间:2023-11-04 10:57:11 25 4
gpt4 key购买 nike

我有一个文件 File1.txt,其中的数据格式如下

*ELEMENT_SHELL
$# eid pid n1 n2 n3 n4 n5 n6
46573 1 48206 48210 48217 48205 0 0
46574 1 48205 48217 48218 48204 0 0
............................................................
.............................................................

我想在第三列中搜索数字,如 48206,并从另一个文件 File2.txt 中搜索它,该文件的格式如下所示

text
text
48205 54.995392 -1.847287e-009 149.449997 0 0
48206 55.995308 -1.879442e-009 149.449997 0 0
48207 56.995224 -1.911598e-009 149.449997 0 0
text
48208 56.995224 -1.911598e-009 149.449997 0 0
...

并将完整的行连同数字一起放回第一个文件中,并将其附加在末尾。 这样 File1.text 看起来像

*ELEMENT_SHELL
$# eid pid n1 n2 n3 n4 n5 n6
46573 1 48206 48210 48217 48205 0 0
46574 1 48205 48217 48218 48204 0 0
....................................................
............................................................
48206 55.995308 -1.879442e-009 149.449997 0 0

对 SED 或 AWK 有什么建议吗?

最佳答案

使用 awk:

awk 'NR == FNR { print; if(NR > 2) { seen[$3] = 1 }; next } seen[$1]' file1 file2

代码的工作原理如下:

NR == FNR {       # while processing the first file
print # print the line (echoing file1 fully)
if(NR > 2) { # from the second line onward
seen[$3] = 1 # remember the third fields you saw
}
next # don't do anything else.
}
seen[$1] # while processing the second file: select lines
# whose first field is one of the remembered fields.

然后您可以将此输出重定向到另一个文件,然后用该文件替换 file1:

awk 'NR == FNR { print; if(NR > 2) { seen[$3] = 1 }; next } seen[$1]' file1 file2 > file1.new && mv file1.new file1

关于linux - 从子文件中的母文件中搜索一个数字,并将子文件中的完整行追加到母文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28411064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com