bash - 是否可以在不对输出文件进行排序的情况下使用 Grep、Sed 或 Awk 或 bash 脚本?
问题描述
我有 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
推荐阅读
- php - 如何获取数组的某些部分并输出到字符串中?
- javascript - 使用 post 参数打开 url
- architecture - ESB 通常会提供多少业务逻辑/抽象
- django - 将查询集 RelatedFields 限制为仅当前相关的对象
- wordpress - 自定义 wp_query,其中 meta_key 是可变的或不需要
- python - Python:如何将字符串转换为 url 安全字符串?
- eclipse - 自动分享git项目遇到问题
- javascript - NavigationDuplicated 不允许导航到当前位置(“/search”)
- python - Rstudio + reticulate + python中的keras出错
- lotus-notes - 如何通过 LotusScript 访问文件资源