gpt4 book ai didi

linux - 在一个文件中搜索给定模式的另一个文件

转载 作者:IT王子 更新时间:2023-10-29 01:15:23 28 4
gpt4 key购买 nike

我正在为 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,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

关于linux - 在一个文件中搜索给定模式的另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20077164/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com