gpt4 book ai didi

bash - 是否可以在不对输出文件进行排序的情况下使用 Grep、Sed 或 Awk 或 bash 脚本?

转载 作者:行者123 更新时间:2023-11-29 09:04:02 24 4
gpt4 key购买 nike

我有 2 个文本文件。 File1 大约有 1,000 行,File2 有 20,000 行。File1 的摘录如下:

Thrust
Alien Breed Special Edition '92
amidar
mario
mspacman
Bubble Bobble (Japan)

File2的摘录如下:

005;005;Arcade-Vertical;;;;;;;;;;;;;;
Alien Breed Special Edition '92;Alien Breed Special Edition '92;Amiga;;1992;Team 17;Action / Shooter;;;;;;;;;;
Alien 8 (Japan);Alien 8 (Japan);msx;;1987;Nippon Dexter Co., Ltd.;Action;1;;;;;;;;;
amidar;amidar;Arcade-Vertical;;;;;;;;;;;;;;
Bubble Bobble (Japan);Bubble Bobble (Japan);msx2;;;;;;;;;;;;;;
Buffy the Vampire Slayer - Wrath of the Darkhul King (USA, Europe);Buffy the Vampire Slayer - Wrath of the Darkhul King (USA, Europe);Nintendo Game Boy Advance;;2003;THQ;Action;;;;;;;;;;
mario;mario;FBA;;;;;;;;;;;;;;
mspacman;mspacman;Arcade-Vertical;;;;;;;;;;;;;;
Thrust;Thrust;BBC Micro;;;;;;;;;;;;;;
Thunder Blade (1988)(U.S. Gold)[128K];Thunder Blade (1988)(U.S. Gold)[128K];ZX Spectrum;;;;;;;;;;;;;;
Thunder Mario v0.1 (SMB1 Hack);Thunder Mario v0.1 (SMB1 Hack);Nintendo NES Hacks 2;;;;;;;;;;;;;;

在 File3(输出文件)中,使用 grep、sed、awk 或 bash 脚本,我想实现以下输出:

Thrust;Thrust;BBC Micro;;;;;;;;;;;;;;
Alien Breed Special Edition '92;Alien Breed Special Edition '92;Amiga;;1992;Team 17;Action / Shooter;;;;;;;;;;
amidar;amidar;Arcade-Vertical;;;;;;;;;;;;;;
mario;mario;FBA;;;;;;;;;;;;;;
mspacman;mspacman;Arcade-Vertical;;;;;;;;;;;;;;
Bubble Bobble (Japan);Bubble Bobble (Japan);msx2;;;;;;;;;;;;;;

例如,当我使用 Grep 生成 File3 时,我发现它会自动对文件内容进行排序。我想保持与 File1 相同的顺序。

我使用的代码示例最终对 File3(我不想要的)进行排序,如下所示:

grep -F -w -f /home/pi/.attract/stats/File1.txt /home/pi/.attract/stats/File2.txt > /home/pi/.attract/stats/File3.txt

最佳答案

使用 awk:

$ awk -F\; 'NR==FNR{a[$1]=$0;next}$1 in a{print a[$1]}' file2 file1

输出:

Thrust;Thrust;BBC Micro;;;;;;;;;;;;;;
Alien Breed Special Edition '92;Alien Breed Special Edition '92;Amiga;;1992;Team 17;Action / Shooter;;;;;;;;;;
amidar;amidar;Arcade-Vertical;;;;;;;;;;;;;;
mario;mario;FBA;;;;;;;;;;;;;;
mspacman;mspacman;Arcade-Vertical;;;;;;;;;;;;;;
Bubble Bobble (Japan);Bubble Bobble (Japan);msx2;;;;;;;;;;;;;;

解释:

awk -F\; '
NR==FNR { # process file2
a[$1]=$0 # hash record to a, use $1 as key
next # process next record
}
($1 in a) { # if file1 entry is found in hash a
print a[$1] # output it
}' file2 file1 # mind the order. this way file1 dictates the output order

关于bash - 是否可以在不对输出文件进行排序的情况下使用 Grep、Sed 或 Awk 或 bash 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52814035/

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