按列匹配并打印到行

时间:2015-03-29 09:53:51

标签: linux awk sed

尝试搜索但找不到任何替代资料

我有2个文件:
1:

asdfdata:tomatch1:asdffdataaa
asdfdata2:tomatch2:asdffdata33
asdf:tomatch3:asdfx

2:

bek:tomatch1:beke  
lek:tomatch3:lekee  
wen:tomatch2:wenne    

我希望通过第二列中的匹配,通过线上的任何数据,然后将其打印到如下所示的行:

asdfdata:tomatch1:asdffdataaa:bek:beke
asdfdata2:tomatch2:asdffdata33:wen:wenne    

我想awk会是最好的,Match two files by column line by line - no key它看起来有点类似! 谢谢你的帮助!!

3 个答案:

答案 0 :(得分:1)

使用join命令,如:

join -t":" -1 2 -2 2 <(sort -t":" -k 2 file1.txt) <(sort -t":" -k 2 file2.txt)

以下是它的工作原理:

-t用于定界仪
-1 - 来自第一个文件第二个字段,由“:”分隔 -2 - 来自第二个文件的第二个字段,由“:”分隔 join需要输入文件在我们想要加入的字段上排序,因此你会看到sort命令,第二个字段用-k选项指定,t选项再次使用delimeter作为冒号(:)并在输入后通过输入连接命令第二场。

答案 1 :(得分:0)

我认为joinsort最简单。假设bash(用于进程替换):

join -t :  -j 2 <(sort -t :  -k 2 file1) <(sort -t : -k 2 file2)

或者,使用awk(如果不能依赖bash并且不需要临时文件):

awk -F : 'NR == FNR { a[$2] = $0; next } { line = a[$2] FS $1; for(i = 3; i <= NF; ++i) line = line FS $i; print line }' file1 file2

那是

NR == FNR {                   # while processing the first file
  a[$2] = $0                  # remember lines by key
  next
}
{                             # while processing the second file
  line = a[$2] FS $1          # append first field to remembered line
                              # from the first file with the current key
  for(i = 3; i <= NF; ++i) {  # append all other fields (except the second)
    line = line FS $i
  }
  print line                  # print result
}

答案 2 :(得分:0)

这可能适合你(GNU sed):

sed -r 's|(.*)(:.*:)(.*)|/\2/s/$/:\1:\3/|' file2 | sed -f - file1

这构造了一个来自file2的sed脚本来对file1运行。