从另一个文件中搜索模式

时间:2013-11-19 16:44:51

标签: linux shell awk grep ksh

我正在为linux shell中的这个问题寻找一个紧凑/优雅的解决方案(如果可能的话,还是ksh)。

给定2个文件,两个文件都包含具有常量结构的行,例如:

档案A

354guitar..06
948banjo...05
123ukulele.04

档案B

354bass....04
948banjo...04

我想在文件A上循环,并在文件B中搜索位置4-11中具有相同内容的行,但在12-13位搜索不同的内容。

对于上述情况,我希望文件B的第二行作为输出,“banjo ...”匹配文件A和05的第二行!= 04。

我当时想用awk,但找不到自己的解决方案:(

谢谢!

2 个答案:

答案 0 :(得分:4)

使用awk非常简单:

$ awk '{a=substr($0,4,8);b=substr($0,12,2)}NR==FNR{c[a]=b;next}a in c&&c[a]!=b' fileA fileB
948banjo...04

或者以更易读的格式,您可以在脚本名称file.awk

中保存以下内容
#!/bin/awk -f
{ # This is executed for every input line (both files)
        a=substr($0,4,8) # put characters 4 through 11 to variable a
        b=substr($0,12,2) # put characters 12 and 13 to variable b
}
NR==FNR{  # This is executed only for the first file 
        c[a]=b  # store into map c index a, value b
        next # Go to the next record (remaining commands ignored)
}
# The remaining is only executed for the second file (due to the next command)
(a in c) && (c[a] != b) # if a is an index of the map c, and the value
                        # we previously stored is not the same as the current b value
                        # then print the current line (this is the default acttion)

并执行如下:

awk -f file.awk fileA fileB

答案 1 :(得分:1)

您可以使用zsh one-liner,例如:

for line in `cat fileA`; do grep '^\d\{3\}$line[4,11]' fileB | grep -v '$line[12,14]$'; done