1

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.

1
  • 2
    When you redirect input from a file awk '...' < file, you lose the ability for awk to populate the often-useful FILENAME variable. Just let awk open the file itself awk '...' file. Commented Feb 23, 2014 at 20:19

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

+1 for this approach, but may has a bug, that can't identify some IDs, such as 0212 and 02120
One could elaborate the generated script with word or field boundary markers, but given the sample data (fixed field length with leading zero padding) that didn't seem necessary. A quick and dirty fix would be s%:\2$%:\1%

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.