简体   繁体   中英

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)
  • next skips the rest of the script and goes to the next line
  • 1 is a condition that is always true, so do the default action, { print }

If you want to make sure that a replacement exists, you can add a condition $1 in a before the second action block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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