Friday, October 28, 2022

[SOLVED] Transposing multiple columns in multiple rows keeping one column fixed in Unix

Issue

I have one file that looks like below

1234|A|B|C|10|11|12  
2345|F|G|H|13|14|15  
3456|K|L|M|16|17|18  

I want the output as

1234|A  
1234|B  
1234|C  
2345|F  
2345|G  
2345|H  
3456|K  
3456|L  
3456|M

I have tried with the below script.

awk -F"|" '{print $1","$2","$3","$4"}' file.dat | awk -F"," '{OFS=RS;$1=$1}1'

But the output is generated as below.

1234  
A  
B  
C  
2345  
F  
G  
H  
3456  
K  
L  
M  

Any help is appreciated.


Solution

What about a single simple awk process such as this:

$ awk -F\| '{print $1 "|" $2 "\n" $1 "|" $3 "\n" $1 "|" $4}' file.dat
1234|A
1234|B
1234|C
2345|F
2345|G
2345|H
3456|K
3456|L
3456|M

No messing with RS and OFS.



Answered By - Jens
Answer Checked By - Robin (WPSolving Admin)