AWK:比较来自两个文件的子字符串并写入第三个文件

use*_*132 1 unix linux shell awk

我正在尝试以这种方式比较两个不同的文件,比如说“file1”和“file2”。如果字符的子串,即位置(8 到 12)处的 5 个字符在文件 1 和文件 2 中都匹配,则从文件 1 中删除匹配的行。最后,将输出写入文件 3。(输出包含不匹配的其余行)与文件匹配 2) 我的输出是文件 1 的不匹配行。输出 (file3) = File1 - File2

File1
-----
aqcdfdf**45555**78782121
axcdfdf**45555**75782321
aecdfdf**75555**78782221
aqcdfdf**95555**78782121

File2
-----
aqcdfdf**45555**78782121
axcdfdf**25555**75782321

File3
-----
aecdfdf**75555**78782221
aqcdfdf**95555**78782121
Run Code Online (Sandbox Code Playgroud)

我试过 awk 但我需要一些东西来查看两个文件的子字符串,因为我的文件中没有分隔符。$ awk 'FNR==NR {a[$1]; next} $1 in a' f1 f2 > file3

Rav*_*h13 5

您能否尝试使用 GNU 中显示的示例进行跟踪、编写和测试awk。一旦对终端上的结果感到满意,然后将以下命令的输出重定向到 > file3(附加 > file3到以下命令)。

awk '{str=substr($0,8,5)} FNR==NR{a[str];next} !(str in a)' file2 file1
Run Code Online (Sandbox Code Playgroud)

说明:为以上添加详细说明。

awk '                  ##Starting awk program from here.
{
  str=substr($0,8,5)   ##Creating str which has sub-string of current line from 8th to 12th character.
}
FNR==NR{               ##Checking condition FNR==NR which will run when Input_file2 is being read.
  a[str]               ##Creating array a with index of str here.
  next                 ##next will skip all further statements from here.
}
!(str in a)            ##Checking condition if str is NOT present in a then print that line from Input_file1.
' file2 file1          ##Mentioning Input_file names here.
Run Code Online (Sandbox Code Playgroud)

  • 超级解释! (3认同)
  • 真的需要向你学习如何在每个答案中添加如此详细的解释。 (2认同)