bash Join命令,留出一行数字

时间:2016-07-15 07:09:18

标签: bash shell

我有两个文件,我想取出第三列中有共同数据的行。但它留下了一排应该匹配的行。

File1中

b b b
4 5 3
c c c

文件2

1 2 3 4
a b c d
e f g h
i j k l
l m n o

输出结果为:

c c c a b d

使用的命令是:

join -1 3 -2 3 --nocheck-order File1.txt File2.txt

即使在放置--nocheck-order

之后,它仍然错过了以3为公共字段的行

编辑:

预期产出:

c c c a b d
3 4 5 1 2 4

2 个答案:

答案 0 :(得分:2)

作为2 sort命令的替代(对于大文件可能非常昂贵)然后是join,您可以使用此单awk命令来获取输出:

awk 'FNR == NR{a[$3]=$0; next} $3 in a{print $3, a[$3], $1, $2, $4}' file1 file2

3 4 5 3 1 2 4
c c c c a b d

<强>解释

NR == FNR {                  # While processing the first file
  a[$3] = $0                 # store the whole line in array a using $3 as key
  next
}

$3 in a {                    # while processing the 2nd file, when $3 is found in array
  print $3,a[$3],$1,$2,$4    # print relevant fields from file2 and the remembered
                             # value from the first file.
}

答案 1 :(得分:1)

您需要对输入进行排序(例如使用process substitution):

// Method that returns the font for buttons and title bar
// Pass in your custom font as a string argument/ parameter
func getFont(fontName: String, size fontSize: CGFloat)-> UIFont {

// Unwrap your custom font here, if font exists "Hooray!" else "Bo-Oh!" return a default one
if let customFont = UIFont(named: fontName, size: fontSize ) {
  return customFont
} else {
// This gets the system default font and returns to you!
  return UIFont(named: defaultFont, size: fontSize )
}

这相当于:

$ join -1 3 -2 3 <(sort -k3 1.txt) <(sort -k3 2.txt)
3 4 5 1 2 4
c c c a b d