首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从另一个文件中搜索给定模式的文件

从另一个文件中搜索给定模式的文件
EN

Stack Overflow用户
提问于 2013-11-19 16:44:50
回答 2查看 77关注 0票数 4

我正在linux中为这个问题提供一个紧凑/优雅的解决方案(如果可能的话,可以使用ksh)。

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

文件A

代码语言:javascript
复制
354guitar..06
948banjo...05
123ukulele.04

档案B

代码语言:javascript
复制
354bass....04
948banjo...04

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

对于上面的情况,我希望B文件的第二行输出,有“班卓琴.”匹配文件A和05!=04的第二行。

我正在考虑使用awk,但自己找不到解决办法:

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-11-19 16:58:38

使用awk非常简单:

代码语言:javascript
复制
$ 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中保存以下内容

代码语言:javascript
复制
#!/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)

执行如下:

代码语言:javascript
复制
awk -f file.awk fileA fileB
票数 4
EN

Stack Overflow用户

发布于 2013-11-19 17:54:16

您可以使用像这个这样的zsh一行:

代码语言:javascript
复制
for line in `cat fileA`; do grep '^\d\{3\}$line[4,11]' fileB | grep -v '$line[12,14]$'; done
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20077164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档