-1

I need a one-liner (that I can put in a dos batch file), preferably using a unix command like AWK or JOIN. The function I need is essentially a more elaborate version of the following JOIN command:

join -j 1 -a 1 file1.txt file2.txt -t "^" > output.txt

[walkthrough: field separators are "^", join key is 1st field of both fields, and not exactly sure what the "-a 1" is doing exactly but it is sticking the bit-to-be joined on the end of the row of the other file, which is what I want.

Now, this one-liner works fine where both files are sorted and there is only one matching line in the 2nd file ... but I need it to try to match up to 4 lines in the 2nd file.

E.g.
file1:

12^blahblah
13^blahblahblahblah
14^blahblahblahblahblahblahblahblah

file2:

12^banana
12^orange
12^apple
13^potato
14^tomato

So I want the output like this:

12^blahblah^banana,orange,apple
13^blahblahblahblah^potato
14^blahblahblahblahblahblahblahblah^tomato

[Doesn't have to be a comma separating the new items]

1
  • wrt Doesn't have to be a comma separating the new items - Why bring up commas at all? Have you had a problem in the past with commands spuriously injecting commas in your text?
    – Ed Morton
    Aug 11, 2016 at 14:38

2 Answers 2

1

You can try this awk command:

awk -F'^' 'NR==FNR{if($1 in a){a[$1]=a[$1]","$2} else {a[$1]=$2}} NR>FNR{print $0 "^" a[$1]}' file2 file1

The script fills an array a with the content of file2 and and append the content of the array when parsing file1

0
1
$ awk -F'^' 'NR==FNR{a[$1]=$0 FS;next} {a[$1] = a[$1] s[$1] $2; s[$1]=","} END{for (i in a) print a[i]}' file1 file2
12^blahblah^banana,orange,apple
13^blahblahblahblah^potato
14^blahblahblahblahblahblahblahblah^tomato
1
  • 1
    Although this code may help to solve the problem, it doesn't explain why and/or how it answers the question. Providing this additional context would significantly improve its long-term value. Please edit your answer to add explanation, including what limitations and assumptions apply. Aug 11, 2016 at 16:28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.