我正在linux中为这个问题提供一个紧凑/优雅的解决方案(如果可能的话,可以使用ksh)。
给定两个文件,两个文件都包含具有固定结构的行,例如:
文件A
354guitar..06
948banjo...05
123ukulele.04档案B
354bass....04
948banjo...04我想在文件A上以某种方式循环,并在文件B中搜索在位置4-11中具有相同内容的行,但在位置12-13中搜索不同的内容。
对于上面的情况,我希望B文件的第二行输出,有“班卓琴.”匹配文件A和05!=04的第二行。
我正在考虑使用awk,但自己找不到解决办法:
谢谢!
发布于 2013-11-19 16:58:38
使用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发布于 2013-11-19 17:54:16
您可以使用像这个这样的zsh一行:
for line in `cat fileA`; do grep '^\d\{3\}$line[4,11]' fileB | grep -v '$line[12,14]$'; donehttps://stackoverflow.com/questions/20077164
复制相似问题