【问题标题】:Is it possible to use Grep, Sed or Awk or a bash script without sorting the output file?是否可以在不对输出文件进行排序的情况下使用 Grep、Sed 或 Awk 或 bash 脚本?
【发布时间】:2019-03-19 17:19:46
【问题描述】:

我有 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

【问题讨论】:

  • 为了清楚起见,您的输出未排序,grep给出的顺序与file2中给出的顺序相同,这是意外排序的情况-不敏感。
  • 谢谢。我从詹姆斯布朗的回答中了解到这一点。我没有意识到这一点,所以知道这一点非常有用。

标签: bash awk sed grep


【解决方案1】:

使用 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

【讨论】:

  • 太棒了。谢谢你。完美运行!这是我的第一个问题。我如何“提高您的声誉”?
猜你喜欢
  • 2018-05-01
  • 1970-01-01
  • 2013-12-11
  • 2022-06-15
  • 2016-02-28
  • 1970-01-01
  • 2012-04-30
  • 2020-01-20
  • 1970-01-01
相关资源
最近更新 更多