0

I have 2 files, Zipcode.txt and Address.csv:

ZipCode.txt
12345
23456
34567
45678

Address.csv
12345,3587 main st,apt j1,city,new jersey
23456,4215 1st st. s.,suite a2,city,new jersey
65432,115 main st,,city,new jersey
45678,654 2nd st n.,city,new jersey

If the zipcode field in Zipcode.txt matches the zipcode field in Address.csv, I want to change the 4th field from city to found. Here's what I want:

12345,3587 main st,apt j1,found,new jersey
23456,4215 1st st. s.,suite a2,found,new jersey
65432,115 main st,,city,new jersey
45678,654 2nd st n.,found,new jersey

This is what I have tried:

awk -F',' 'BEGIN{OFS=FS}NR==FNR{a[$1]=1;next}a[$1]{$4="found"}1' Address.csv ZipCode.txt
3
  • Do you want to search for any zip code in the file or only on the corresponding line (first line in the first file must match the first line in the second file)?
    – simlev
    Commented Jun 4, 2019 at 8:52
  • The zip code can be on any line of the file, not always the first line.
    – bullet117
    Commented Jun 4, 2019 at 13:47
  • Very well, then see my answer below.
    – simlev
    Commented Jun 4, 2019 at 13:49

1 Answer 1

0

This will search whether the zip code in the first field of Address.csv is found anywhere in Zipcode.txt:

awk -F, -v OFS="," 'NR==FNR {a[$1]++;next} $1 in a {$4="found"} 1' Zipcode.txt Address.csv

Output:

12345,3587 main st,apt j1,found,new jersey
23456,4215 1st st. s.,suite a2,found,new jersey
65432,115 main st,,city,new jersey
45678,654 2nd st n.,city,found

Note that the last line is not as expected, because city is not the fourth field in the input: a comma is likely missing in the last line of Address.csv.

3
  • simlev, when I ran you command:
    – bullet117
    Commented Jun 4, 2019 at 14:33
  • I got it to work thanks, can I ask another question on this same thing or should I start a new question?
    – bullet117
    Commented Jun 4, 2019 at 15:16
  • @bullet117 You should always ask a new question, just add a link to this question if they are related.
    – simlev
    Commented Jun 4, 2019 at 15:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .