vid*_*har 1 linux shell awk grep sed
我有两个文件如下:
文件1
"Connect"    CONNECT_ID="12"
"Connect"    CONNECT_ID="11"
"Connect"    CONNECT_ID="122"
"Connect"    CONNECT_ID="109"
Run Code Online (Sandbox Code Playgroud)
文件2
"Quit"    CONNECT_ID="12"
"Quit"    CONNECT_ID="11"
Run Code Online (Sandbox Code Playgroud)
文件内容不完全相同,但与上述类似,记录数量最少为100,000.
现在我想将结果如下所示显示到file1中(意味着最终结果应该在file1中)
"Connect"    CONNECT_ID="122"
"Connect"    CONNECT_ID="109"
Run Code Online (Sandbox Code Playgroud)
我使用了类似下面的while循环:
awk {'print $2'} file2 | sed "s/CONNECTION_ID=//g" > sample.txt
while read actual; do
    grep -w -v $actual file1 > file1_tmp
    mv -f file1_tmp file1
done < sample.txt
Run Code Online (Sandbox Code Playgroud)
在这里,我根据示例调整了我的代码.所以它可能会也可能不会奏效.
我的问题是循环重复超过1小时才能完成整个过程.
所以任何一个可以建议我如何达到同样与像使用任何其他方式diff或comm或sed或awk或任何其他的Linux命令,它会运行得更快?
这里主要是我要消除这个典型的大while循环.
大多数UNIX工具都是基于行的,因为您没有整行匹配,这意味着grep,comm并且diff不在窗口.提取您想要的基于字段的信息awk是完美的:  
$ awk 'NR==FNR{a[$2];next}!($2 in a)' file2 file1
"Connect"    CONNECT_ID="122"
"Connect"    CONNECT_ID="109"
Run Code Online (Sandbox Code Playgroud)
要将结果存储回来,file1您需要将输出重写为临时文件,然后将文件移动到file1如下所示:
$ awk 'NR==FNR{a[$2];next}!($2 in a)' file2 file1 > tmp && mv tmp file1
Run Code Online (Sandbox Code Playgroud)
说明:
每个读取的记录的awk变量NR递增,即每个文件中的每一行.FNR每个记录的变量都会递增,但每个文件都会重置.
NR==FNR    # This condition is only true when reading file1
a[$2]      # Add the second field in file1 into array as a lookup table
next       # Get the next line in file1 (skips any following blocks)
!($2 in a) # We are now looking at file2 if the second field not in the look up
           # array execute the default block i.e print the line 
Run Code Online (Sandbox Code Playgroud)
要修改此命令,只需更改匹配的字段即可.在您的实际情况下,如果您想要将字段1 file1与字段4 匹配,file2那么您将执行以下操作:
$ awk 'NR==FNR{a[$1];next}!($4 in a)' file2 file1
Run Code Online (Sandbox Code Playgroud)