如何搜索 file1.txt 和 file2.txt 中匹配的字符并将输出打印到新文件

问题描述 投票:0回答:2

问题: 我需要有关任务的帮助,其中我有两个文本文件 file1.txt 和 file2.txt。这些文件具有相似的格式,但名称位于不同的行号上,并且它们具有不同的行数。任务是检查 file1.txt 中的哪些名称与 file2.txt 中的名称匹配,然后将 file2.txt 中的匹配行打印到新文件 (file3.txt) 中。

文件格式示例: 文件1.txt:

NAME:FLAT
Jerome:Flat 6
Jimmy:Flat 4

file2.txt:

0:NAME:JOB:MONEY:FLAT
1:Bob:Developer:$500:Flat 7
2:Jerome:Gardener:$50:Flat 6
3:Cindy:Graphics:$100:Flat 5
4:Jimmy:Mod:$150:Flat 4

我想要实现的目标: 我想比较 file1.txt 中的名称(例如 Jerome、Jimmy)并检查它们是否也存在于 file2.txt 中。

我只想输出 file2.txt 中的匹配行。 file2.txt 中未出现在 file1.txt 中的任何名称都应被忽略。例如,“Bob”和“Cindy”出现在 file2.txt 中,但不出现在 file1.txt 中,因此应忽略它们。 file2.txt 中的匹配行(例如“Jerome”和“Jimmy”)应复制到新文件 (file3.txt) 中。

预期输出示例: 如果 file1.txt 中的 Jerome 和 Jimmy 与 file2.txt 中的行匹配,则输出文件 (file3.txt) 应如下所示:

file3.txt:

2:Jerome:Gardener:$50:Flat 6
4:Jimmy:Mod:$150:Flat 4

我尝试过的: 这是我到目前为止尝试过的代码,它使用 awk 进行匹配:

awk -F ":" 'FNR==NR{a[$1];next}($1 in a){print}' file2.txt file1.txt > file3.txt

我需要帮助: 如果有人能帮助我弄清楚这是否可行或提供更好的解决方案,我将非常感激!

bash awk grep formatting text-processing
2个回答
4
投票

根据您显示的示例,您可以尝试以下操作吗?使用 GNU 编写和测试

awk

awk '
BEGIN  { FS=":" }
FNR==1 { next   }
FNR==NR{
  arr[$1]
  next
}
($2 in arr)
' file1.txt file2.txt

说明: 为上述内容添加详细说明。

awk '                    ##Starting awk program from here.
BEGIN  { FS=":" }        ##Starting BEGIN section from here and setting FS as : here.
FNR==1 { next   }        ##Checking if this is first line in any of Input_file then simply go to next line.
FNR==NR{                 ##This condition will be TRUE when file1.txt is being read.
  arr[$1]                ##Creating array with $1 as key here.
  next                   ##next will skip all further statements from here.
}
($2 in arr)              ##Checking condition if 2nd fueld is in arr then print line from file2.txt
' file1.txt file2.txt    ##Mentioning Input_file names here.

1
投票

使用一些 GNU 工具:

join -t ":" -1 1 -2 2 <(sed 1d File1.txt | sort) <(sort -t ":" -k 2,2 File2.txt) -o 2.1,2.2,2.3,2.4,2.5

输出:

2:杰罗姆:园丁:50 美元:6 号公寓
4:吉米:模组:150 美元:平 4

参见:

info join
man sort

© www.soinside.com 2019 - 2024. All rights reserved.