【问题标题】:Searching a column in another column of another file in linux在linux中搜索另一个文件的另一列中的列
【发布时间】:2018-08-20 18:58:44
【问题描述】:

我有一个多列文件如下:

file1.txt
1 12 220 AJ-lett-K-MD
2 33 312 BCJ-23-660-numm
4 22 55  lett-C-100b
5 52 59  lett-C-100bc
6 82 995 numm-X-aab

还有,

file2.txt

1 338 339 89839,lett;847447,AJ-lett-K-MD
2 223 443 numm;33920;numm3,AJ-lett-K-MD,50
3 443 223 AFFVlett-C-100b,lett-C-100b
4 542 442 187;lett-C-100bc
7 765 765 XXXX-CCC

我正在尝试在file2.txt4th 列中搜索file1.txt4th 列,如果存在,则打印file1.txt1st,2nd,3rd 列和4thfile2.txt,在file2.txt的内容之上。

例如,file1.txt1st line4th 列是AJ-lett-K-MD。它存在于file2.txt1st and 2nd lines4th 列中。

所以,我需要打印1st linefile1.txt1st,2nd and 3rd colums1st and 2nd linesfile2.txt4th columns

所以预期的输出应该是:

expected.txt
1 338 339  89839,lett;847447,AJ-lett-K-MD --> original
1 12  220  89839,lett;847447,AJ-lett-K-MD --> combination of file1 and file2
2 223 443  numm;33920;numm3,AJ-lett-K-MD,50 --> original
1 12  220  numm;33920;numm3,AJ-lett-K-MD,50 --> combination of file1 and file2
3 443 223  AFFVlett-C-100b,lett-C-100b --> original
4 22  55   AFFVlett-C-100b,lett-C-100b --> combination
4 542 442  187;lett-C-100bc --> original
4 22  55   187;lett-C-100bc --> combination
5 52  59   187;lett-C-100bc --> combination
7 765 765 XXXX-CCC

我的尝试是将file1.txt的单词作为变量,然后在file2.txt中搜索:

grep -v ^# file1.txt | while read a b c d; do echo a=$a b=$b c=$c d=$d;
grep "$d" file2.txt

它给出:

1 338 339 89839,lett;847447,AJ-lett-K-MD
2 223 443 numm;33920;numm3,AJ-lett-K-MD,50
3 443 223 AFFVlett-C-100b,lett-C-100b
4 542 442 187;lett-C-100bc

但是,我不知道如何进行。使用awkpython 会更好吗?任何帮助表示赞赏!

PS : file1.txt 中的 4th 列不是唯一的,我需要所有匹配项(不仅仅是第一个)。

重要编辑:我以不同且更好的方式解释了我的问题:Searching partial match of string in a column in a column of another file 他们搜索相似但不同的输出。

【问题讨论】:

标签: linux string search awk grep


【解决方案1】:

awk 来救援!

假设 file1 的键是唯一的并且需要第一个匹配项

$ awk 'NR==FNR{a[$4]=$1 FS $2 FS $3; next}
              {for(k in a) 
                 if("," $4 "," ~ "(,|;)" k "(,|;)") 
                    {print; print a[k],$4; break}}' file1 file2

如果您需要所有匹配项,请删除 break

如果键不是唯一的,这种方法只会从第一个文件中获取键值的最后一个实例。以下代码将处理非唯一键和多个匹配项

$ awk 'NR==FNR{a[++c[$4],$4]=$1 FS $2 FS $3; next}
              {for(k in c)
                 if("," $4 "," ~ "(,|;)" k "(,|;)") 
                   for(j=1;j<=c[k];j++) print $0 ORS a[j,k],$4}' file1 file2

【讨论】:

  • 加 1,但我会使用带有单词边界的 $4 ~ "\\\\&lt;" k "\\\\&gt;"
  • 我明白了,但似乎只有;, 用作分隔符。例如- 是令牌的一部分,不应被视为单词边界。
  • 我应该添加到我的帖子中,因为键不是唯一的......而且我需要所有匹配项
  • 我尝试使用 awk -F '\t' '$1 == 1 {print $0}' file1.txt | while read line; do 添加迭代,但它只获得最后一个匹配项
  • 我们用分隔符将文字和行包装起来,以消除任何错误匹配。那就是强制正则表达式始终匹配完整的单词而不是子字符串。为此,您至少需要一个分隔符,我猜在这种情况下您有两个 [;,],两者都可以。
猜你喜欢
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多