Awk 匹配两个文件并保留重复文件
文件1 文件2Awk 匹配两个文件并保留重复文件,awk,grep,Awk,Grep,文件1 文件2 pears oranges apples pear pears pears apples apples grapes grapes straw 我需要将文件1与2进行比较并获得匹配项。如果它是重复的,也包括它 我试过的 apples pear grapes straw 这让我 grep -f file 1 file 2 但是我想包括映射到文件2的副本 apples pear grapes straw 你能试试下面的吗 apples apples apples p
pears
oranges
apples
pear
pears
pears
apples
apples
grapes
grapes
straw
我需要将文件1与2进行比较并获得匹配项。如果它是重复的,也包括它
我试过的
apples
pear
grapes
straw
这让我
grep -f file 1 file 2
但是我想包括映射到文件2的副本
apples
pear
grapes
straw
你能试试下面的吗
apples
apples
apples
pear
grapes
grapes
straw
解释:为上述代码添加解释
awk 'FNR==NR{a[$0]=(a[$0]?a[$0] ORS:"")$0;next} ($0 in a){print a[$0]}' Input_file1 Input_file2
输出如下
awk ' ##Starting awk program here.
FNR==NR{ ##Checking condition FNR==NR which will be TRUE when Input_file1 is being read.
a[$0]=(a[$0]?a[$0] ORS:"")$0 ##Creating an array named a whose index is $0 and its keep concatenating its own values with new line and current line value.
next ##next will skip all further statements from here.
} ##Closing BLOCK for FNR==NR condition here.
($0 in a){ ##Checking condition if $0 is present in array a then do following.
print a[$0] ##Printing array a value whose index is $0.
}
' Input_file1 Input_file2 ##Mentioning Input_file names here.
你能试试下面的吗
apples
apples
apples
pear
grapes
grapes
straw
解释:为上述代码添加解释
awk 'FNR==NR{a[$0]=(a[$0]?a[$0] ORS:"")$0;next} ($0 in a){print a[$0]}' Input_file1 Input_file2
输出如下
awk ' ##Starting awk program here.
FNR==NR{ ##Checking condition FNR==NR which will be TRUE when Input_file1 is being read.
a[$0]=(a[$0]?a[$0] ORS:"")$0 ##Creating an array named a whose index is $0 and its keep concatenating its own values with new line and current line value.
next ##next will skip all further statements from here.
} ##Closing BLOCK for FNR==NR condition here.
($0 in a){ ##Checking condition if $0 is present in array a then do following.
print a[$0] ##Printing array a value whose index is $0.
}
' Input_file1 Input_file2 ##Mentioning Input_file names here.
您正在匹配固定字符串,并且希望匹配整行,因此将
-F
和-x
选项添加到grep
只需将file2设置为模式文件:
apples
apples
apples
pear
grapes
grapes
straw
您正在匹配固定字符串,并且希望匹配整行,因此将
-F
和-x
选项添加到grep
只需将file2设置为模式文件:
apples
apples
apples
pear
grapes
grapes
straw
如果您在grep中更改文件顺序,它将为您提供所需的记录,但在原始顺序中,还将添加正确的选项
grep -Fxf file2 file1
但是,如果您希望将它们按文件2顺序排列,awk
是一个更好的解决方案
这里有一个没有awk的解决方案
$ grep -xFf file2 file1
apples
pear
apples
apples
grapes
grapes
straw
$join-22如果您在grep中更改文件顺序,它将按原始顺序为您提供所需的记录,同时添加正确的选项
grep -Fxf file2 file1
但是,如果您希望将它们按文件2顺序排列,awk
是一个更好的解决方案
这里有一个没有awk的解决方案
$ grep -xFf file2 file1
apples
pear
apples
apples
grapes
grapes
straw
$join-2 2请确保在您的示例中的两个文件中都包含部分匹配项,以便我们了解如何处理它们,例如菠萝与苹果、葡萄柚与葡萄。@ed,已经有“梨”和“梨”了。@Glenjackman啊,谢谢,我错过了。现在我们只需要一些相反方向的类似内容来结束它,例如,将苹果添加到文件1。请确保在您的示例中的两个文件中都包含部分匹配项,以便我们可以看到如何处理它们,例如菠萝与苹果、葡萄柚与葡萄。@ed,已经有“梨”和“梨”了。@Glenjackman啊,谢谢,我错过了。现在,我们只需要在相反的方向上使用类似的东西来包装它,例如,将apple添加到file1。