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
使用Bash从文件中提取不同的行_Bash_Comm - Fatal编程技术网

使用Bash从文件中提取不同的行

使用Bash从文件中提取不同的行,bash,comm,Bash,Comm,我有两个文件,我使用comm-23file1file2命令来提取文件之间不同的行 我还需要一些东西来提取不同的行,但同时保留字符串行。 例子: 文件1: 文件2: line_1: This is line1 line_2: This is line2 line_3: This is line3 我需要这个输出: 差异文件1文件2: line_1: This is line0. 总之,我需要提取差异,就像文件开头没有行\u$NR一样,但当我打印结果时,我还需要打印行\u$NR。尝试使用awk

我有两个文件,我使用comm-23file1file2命令来提取文件之间不同的行

我还需要一些东西来提取不同的行,但同时保留字符串行。 例子: 文件1:

文件2:

line_1: This is line1
line_2: This is line2
line_3: This is line3
我需要这个输出: 差异文件1文件2:

line_1: This is line0.
总之,我需要提取差异,就像文件开头没有行\u$NR一样,但当我打印结果时,我还需要打印行\u$NR。

尝试使用awk

输出:

line_1: This is line0
简短描述


此awk线较长,但无论差异位于何处,它都可以工作:

awk 'NR==FNR{a[$NF]=$0;next}a[$NF]{a[$NF]=0;next}7;END{for(x in a)if(a[x])print a[x]}' file1 file2
测试:


如果差异位于文件2中,则此命令失败。换句话说,如果两个文件都有差异,那么anwer中的awk方法将不起作用。@Kent同意。但是这个解决方案是基于OP的comm-23file1file2命令的,我相信这意味着file1所特有的行。如果我遗漏了什么,请纠正我,这是对的。实际上,我需要在file1和file2之间进行某种区分。我使用的是comm-23 file1 file2和comm-23 file2file1@georgiana_e那么你要找的是通信2。在这种情况下,diff是更好的命令。Bdw如果您只是想遵循您的方法,那么您能否通过交换文件1和文件2将相同的逻辑应用于我的解决方案?您的解决方案似乎可行,但请您解释一下。我不明白它在做什么。我想在文件之间进行某种区分,但不比较行号,只打印行号。我不知道comm是否合适。您的diff版本可能有生成类似comm的并排输出的选项。我想在没有行号的file1 file2之间进行diff,然后使用awk插入行号?我不希望测试f2 f1返回与测试f1相同的输出。同样在文件2中,我用第5行更改了第2行,输出为:第2行:第5行:第1行:第0行:第3行:第2行
line_1: This is line0
awk -F: '             # Set filed separator as ':'. $1 contains line_<n> and $2 contains 'This is line_<m>'
    NR==FNR {         # If Number of records equal to relative number of records, i.e. first file is being parsed
        a[$2];        # store $2 as a key in associative array 'a'
        next          # Don't process further. Go to next record.
    } 
    !($2 in a)        # Print a line if $2 of that line is not a key of array 'a'
' file2 file1
awk -F'line_[0-9]+:' 'NR==FNR {a[$2]; next} !($2 in a)' file2 file1
awk 'NR==FNR{a[$NF]=$0;next}a[$NF]{a[$NF]=0;next}7;END{for(x in a)if(a[x])print a[x]}' file1 file2
kent$  head f*
==> f1 <==
line_1: This is line0
line_2: This is line1
line_3: This is line2
line_4: This is line3

==> f2 <==
line_1: This is line1
line_2: This is line2
line_3: This is line3

#test f1 f2
kent$  awk 'NR==FNR{a[$NF]=$0;next}a[$NF]{a[$NF]=0;next}7;END{for(x in a)if(a[x])print a[x]}' f1 f2
line_1: This is line0

#test f2 f1:    
kent$  awk 'NR==FNR{a[$NF]=$0;next}a[$NF]{a[$NF]=0;next}7;END{for(x in a)if(a[x])print a[x]}' f2 f1
line_1: This is line0