user3344199
user3344199

Reputation: 107

use sed awk to replace variable defined in another file

I have a users.txt file in the format:

User:CityID
Carl:0212
Syd:0312
Rick:9323

and a city.txt file in the format

Anaheim:0212
San Jose:0312

I need to replace every CityID in the users.txt with the city name from the city.txt file. How can I achieve this using sed and awk?

I can get the column of CityID's using awk using:

awk -F$'\:' '{print $2}'< users.txt

but how do it replace them with the corresponding city name?

Thank you.

Upvotes: 1

Views: 983

Answers (2)

tripleee
tripleee

Reputation: 189948

You can use sed to transform city.txt into a sed script:

sed 's/\([^:]*\):\(.*\)/s%\2%\1%g/' city.txt

then feed that to a second sed instance to process users.txt:

sed 's/\([^:]*\):\(.*\)/s%\2%\1%g/' city.txt |
sed -f - users.txt

Not all sed variants will accept a script file on standard input; you'll have to resort to a temporary file in that case.

Upvotes: 2

jaypal singh
jaypal singh

Reputation: 77185

This would work:

awk 'BEGIN{FS=OFS=":"}NR==FNR{a[$2]=$1;next}{$2=a[$2]}1' city.txt user.txt
  • BEGIN{FS=OFS=":"} : We set the Input and Output Field Separator to :

  • NR==FNR{a[$2]=$1;next} : We read the city file and create an array to store City Name indexed at City ID

  • {$2=a[$2]} : We replace the second field in user.txt by referencing the array

  • 1 : This is to print the line

Upvotes: 5

Related Questions