加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 在一个文件中搜索另一个模式

发布时间:2020-12-13 23:09:24 所属栏目:Linux 来源:网络整理
导读:我正在为 linux shell中的这个问题寻找一个紧凑/优雅的解决方案(如果可能,请使用ksh). 给定2个文件,两个文件都包含具有常量结构的行,例如: 档案A. 354guitar..06948banjo...05123ukulele.04 文件B. 354bass....04948banjo...04 我想在文件A上循环,并在文件B
我正在为 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,但找不到自己的解决方案:(

谢谢!

解决方法

用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,8) # put characters 4 through 11 to variable a
        b=substr($0,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读