用awk比较文件
嗨,我有两个相似的文件(都有3列)。我想检查这两个文件是否包含相同的元素(但以不同的顺序列出)。首先我想用awk比较文件
"xyz" 0 0
"aba" 0 0
"xxx" 0 0
"abc" 1 1
我怎么能做到这一点用awk只比较第一列
FILE1.TXT
"aba" 0 0
"abc" 0 1
"abd" 1 1
"xxx" 0 0
FILE2.TXT?我试图看看,但我发现只有复杂的例子。如果我还想在比较中包括另外两列呢?输出应该给我匹配元素的数量。
要打印普通元素在这两个文件:
$ awk 'NR==FNR{a[$1];next}$1 in a{print $1}' file1 file2
"aba"
"abc"
"xxx"
说明:
NR
和FNR
是存储的记录总数和记录当前文件的数量awk
变量(默认记录是一行)。
NR==FNR # Only true when in the first file
{
a[$1] # Build associative array on the first column of the file
next # Skip all proceeding blocks and process next line
}
($1 in a) # Check in the value in column one of the second files is in the array
{
# If so print it
print $1
}
如果你要匹配的整行,然后使用$0
:
$ awk 'NR==FNR{a[$0];next}$0 in a{print $0}' file1 file2
"aba" 0 0
"xxx" 0 0
或特定的一组列:
$ awk 'NR==FNR{a[$1,$2,$3];next}($1,$2,$3) in a{print $1,$2,$3}' file1 file2
"aba" 0 0
"xxx" 0 0
由于awk脚本的解释而特别投票,谢谢! – vfilby 2016-02-24 05:00:01
@iiSeymour如果在关联数组中找到file2的第一个cloumn,如何打印file1的第二个cloumn? – 2017-03-06 06:26:37
要打印匹配元件的数量,这里有一个使用方法awk
:
awk 'FNR==NR { a[$1]; next } $1 in a { c++ } END { print c }' file1.txt file2.txt
个
结果使用您的输入:
3
如果你想添加额外的列(例如,列一,二,三层),使用pseudo-multidimensional array:
awk 'FNR==NR { a[$1,$2,$3]; next } ($1,$2,$3) in a { c++ } END { print c }' file1.txt file2.txt
结果使用你的输入:
2
+1。由于OP的文件只有3列,所以使用'a [$ 0]'而不是'a [$ 1,$ 2,$ 3]'会更好。但是,任何文件中的任何不匹配的不可见尾随空格都可能导致意外输出。也许使用rtrim或gsub。 – 2013-06-03 21:15:39
像这样使用它 - > za $ awk'FNR == NR {a [$ 1];下一步}!($ a中)END {print $ 1}'test.csv test2.csv打印不匹配的记录。 – zee 2017-08-22 04:15:57
@zee:感谢您的投票,但您不需要您的“END”块 – Steve 2017-08-22 05:36:48
http://theunixshell.blogspot.in/2012/12/i-have-two-files-file-1-conta ins-3.html – Vijay 2014-03-29 13:48:12