Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
比较linux(bash)中的两个平面文件,将缺少的内容放在第一个文件中?_Linux_Bash_Scripting - Fatal编程技术网

比较linux(bash)中的两个平面文件,将缺少的内容放在第一个文件中?

比较linux(bash)中的两个平面文件,将缺少的内容放在第一个文件中?,linux,bash,scripting,Linux,Bash,Scripting,我目前正在尝试比较bash中的两个平面文件。第一个文件将有三列以|分隔,第二个文件将有两列以|分隔。我想将第二个文件中缺少的输入放入第一个文件中。我只关心从文件2到文件1中接管两个缺少的列 示例文件 文件一: a |蓝| 3 b |黄色| 1 c |绿色| 2 文件二: 蓝色 b |黄色 c|绿色 d|紫色 输出文件: a |蓝| 3 b |黄色| 1 c |绿色| 2 d|紫色 这应该起作用: # Set the input field separator to "|" awk -F'|' '

我目前正在尝试比较bash中的两个平面文件。第一个文件将有三列以|分隔,第二个文件将有两列以|分隔。我想将第二个文件中缺少的输入放入第一个文件中。我只关心从文件2到文件1中接管两个缺少的列

示例文件

文件一:

a |蓝| 3

b |黄色| 1

c |绿色| 2

文件二:

蓝色

b |黄色

c|绿色

d|紫色

输出文件:

a |蓝| 3

b |黄色| 1

c |绿色| 2

d|紫色

这应该起作用:

# Set the input field separator to "|"
awk -F'|' '

# Load the second file into an array called "a". NR==FNR allows us to perform this action
# until first file is complete 
NR==FNR { a[$0]; next }

# We check the existence of first and second column of first file in array. If it is present
# we delete that array element. 1 at the end allows us to print the line from first file as is. 
($1 FS $2 in a) { delete a[$1 FS $2] }1

# This action takes place at the very end. Whatever is left in our array we iterate through
# and print it. This can cause the output to appear in any order hence sort is needed. 
END { for (l in a) print l }' f2 f1
输出:


你给我们看了两个文件;让我们看看你希望他们如何处理手术。对此我很抱歉。我已经提供了一个例子,说明了在流程完成后,一个文件的输出文件应该是什么样子。这几乎就是我想要的。现在,最好的方法是什么来确保它是按第1列排序的,并且f1是被重写的,因此它看起来像您示例中的输出。您可以通过管道将输出排序为类似于awk…|排序-t'|'-k1。GNU awk 4.1允许内嵌更改。如果您没有,最好的选择是将其重新定向到新文件并重命名。所以啊…|排序…>谢谢你的帮助。最后一个问题。你介意简要介绍一下这些旗子的作用吗,或者只是简单的解释一下。我希望以后能更好地理解这一点。@user2607210已更新以添加注释。希望有帮助。
$ head f*
==> f1 <==
a|blue|3
c|green|2
b|yellow|1

==> f2 <==
a|blue
c|green
b|yellow
d|purple

$ awk -F'|' '
NR==FNR { a[$0]; next }
($1 FS $2 in a) { delete a[$1 FS $2] }1
END { for (l in a) print l }' f2 f1
a|blue|3
c|green|2
b|yellow|1
d|purple