我必须从一个文件中读取 ids 并在第二个 xml 文件中搜索它,如果找到则将整行写入第三个文件。文件 1 为 111 MB,文件 2 为 40 GB
文件1.xml
id1
id2
id5
Run Code Online (Sandbox Code Playgroud)
文件2.xml
<employees>
<employee><id>id1</id><name>test1</name></employee>
<employee><id>id2</id><name>test2</name></employee>
<employee><id>id3</id><name>test3</name></employee>
<employee><id>id4</id><name>test4</name></employee>
<employee><id>id5</id><name>test5</name></employee>
<employee><id>id6</id><name>test6</name></employee>
</employees>
Run Code Online (Sandbox Code Playgroud)
File3.xml:结果
<employee><id>id1</id><name>test1</name></employee>
<employee><id>id2</id><name>test2</name></employee>
<employee><id>id5</id><name>test5</name></employee>
Run Code Online (Sandbox Code Playgroud)
我用 grep 试过了
grep -i -f file1.xml file2.xml >> file3.xml
Run Code Online (Sandbox Code Playgroud)
但它给出了内存耗尽错误。
我用循环和 awk 命令尝试的另一种方法。
#while read -r id;do
#awk -v pat="$id" '$0~pat' file2.xml >> file3.xml
#done < file1.xml
Run Code Online (Sandbox Code Playgroud)
它也花费了太多时间。对此最好的解决方案是什么?
使用您显示的示例,请尝试以下awk代码。用 GNU 编写和测试awk。
awk -v FPAT='<id>[^<]*</id>' '
FNR==NR{
arr["<id>"$0"</id>"]
next
}
($1 in arr)
' file1.xml file2.xml
Run Code Online (Sandbox Code Playgroud)
说明:对上述内容添加详细说明。
awk -v FPAT='<id>[^<]*</id>' ' ##Starting awk program and setting FPAT to <id>[^<]*<\\/id>
FNR==NR{ ##Checking condition which will be TRUE when file1.xml is being read.
arr["<id>"$0"</id>"] ##Creating an array arr which has index of <id> $0 </id> here.
next ##next will skip all further statements from here.
}
($1 in arr) ##Checking condition if $1 is present in arr then print that line.
' file1.xml file2.xml ##Mentioning Input_file names here.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
103 次 |
| 最近记录: |