简体   繁体   English

如何使用 Bash 使用另一个文本文件中存在的转换替换文本文件列中的名称

[英]How to Replace Names in Column of a Text File, Using a Conversion Present in Another Text File With Bash

I did a search, and none of the other posts fit my situation.我进行了搜索,其他帖子都不适合我的情况。 Basically, I have a long master text file that looks something like this:基本上,我有一个很长的主文本文件,看起来像这样:

Group1 0 100
Group2 100 200
Group3 200 300
Group4 300 400

Ect..等..

I need to replace the names in the master text file, using another text file that lists what they should be converted to.我需要替换主文本文件中的名称,使用另一个列出它们应该转换成什么的文本文件。 That conversion text file looks like this:该转换文本文件如下所示:

Group1 Team1
Group2 Team2
Group3 Team2
Group4 Team3

So by using a script, I want to convert the master text file as such:因此,通过使用脚本,我想将主文本文件转换为:

Team1 0 100
Team2 100 200
Team2 200 300
Team3 300 400

Again, these are big files, and they are not the same lengths.同样,这些都是大文件,而且它们的长度不同。 Any help is MUCH appreciated!任何帮助深表感谢!

Read the conversion list into an array, then use it to replace the first field in the original file:将转换列表读入数组,然后用它替换原文件中的第一个字段:

awk 'NR == FNR { a[$1] = $2; next } { $1 = a[$1] } 1' conversion.txt original.txt
  • NR == FNR condition targets the first file (total line number equals file line number) NR == FNR条件以第一个文件为目标(总行数等于文件行数)
  • next skips the rest of the script and goes to the next line next跳过脚本的其余部分并转到下一行
  • 1 is a condition that is always true, so do the default action, { print } 1是一个始终为真的条件,因此默认操作{ print }

If you want to make sure that a replacement exists, you can add a condition $1 in a before the second action block.如果要确保存在替换,可以在第二个操作块之前$1 in a添加条件$1 in a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM