3

I am wondering how to process information as following:

mapping.txt:

80  001 002
81  011 012 013 014
82  021 022
...

input.txt:

81  103823044
80  103823054
81  103823064
...

Desired output.txt:

103823044|011|
103823044|012|
103823044|013|
103823044|014|
103823054|001|
103823054|002|
103823064|011|
103823064|012|
103823064|013|
103823064|014|

I've done simple mapping wherein the column numbers are fixed but I'm unsure of how to map a dynamic number of columns to the desired output

  • Is using awk a requirement, or do you have the option of using a different language that might make this easier? – godlygeek Jun 17 '15 at 17:48
  • You have changed your input but have not updated your output. What output do you expect from the example files you gave us? – terdon Jun 17 '15 at 18:27
1

You can try following:

awk 'NR == FNR { x[$1,$2] = $1; next; } { for (i in x) { if (x[i] == $1) { split(i,t,SUBSEP); for (z = 2; z <= NF; z++) { print t[2] "|" $z "|"; } } } }' input.txt mapping.txt

The first block is executed while reading the file input.txt. It is achieved by condition NR == FNR which is true while the first file is read. In the first block we create an array x with keys from first ans second column and values from first column. The second block is executed for the file mapping.txt because of next in the first block. In the second block we check for every key in array x if value from column 1 exist as value in array x, and if exists extract second part of the key with split and we print in a loop this value and values from second column till last column (NF - number of fields in current record).

  • Since the OP is a self-proclaimed awk newbie, could you explain a little about how this would work? – roaima Jun 17 '15 at 16:39
  • @roaima, sorry, I'll edit it. – taliezin Jun 17 '15 at 16:41
  • This works if the first column in the input file is unique, but it's not... I've updated my question to reflect that change – K - Jun 17 '15 at 17:28
  • @K- answer edited. – taliezin Jun 17 '15 at 17:42
  • excellent, works like a charm... thanks! I did not know you could do multi-dimensional arrays with awk! This is great!! – K - Jun 17 '15 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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