Sunday, October 9, 2022

[SOLVED] Splitting text to column

Issue

i have case to splitting text like sample

A|B|C|D| 3#1#1#;1#4#4;5#1#4;|E|F|0
AE|B1|CC|DE| |EX|FF|0
AR|BE|CA|D1| 5#6#3#;4#3#4;|ED|G|

I need the text to be like this

A|B|C|D| 3#1#1#;1#4#4;5#1#4;|E|F|0|3|1|1
A|B|C|D| 3#1#1#;1#4#4;5#1#4;|E|F|0|1|4|4
A|B|C|D| 3#1#1#;1#4#4;5#1#4;|E|F|0|5|1|4
AE|B1|CC|DE| |EX|FF|0|||
AR|BE|CA|D1| 5#6#3#;4#3#4;|ED|G||5|6|3
AR|BE|CA|D1| 5#6#3#;4#3#4;|ED|G||4|3|4

i already try using

awk 'BEGIN{FS=OFS="|"} {split($5,a,/;/); for (i in a) {if (a[i]) $9=a[i]; else next; gsub(/#/,"|",$9); print}}

however the if the $5 is having space only, it wont adding the column.


Solution

Using any awk:

$ cat tst.awk
{
    tgt = ( /;/ ? $2 : "###;")
    gsub(/#/,"|",tgt)
    n = split(tgt,a,/\|?;/)
    for ( i=1; i<n; i++ ) {
        print $0 "|" a[i]
    }
}

$ awk -f tst.awk file
A|B|C|D| 3#1#1#;1#4#4;5#1#4;|E|F|0|3|1|1
A|B|C|D| 3#1#1#;1#4#4;5#1#4;|E|F|0|1|4|4
A|B|C|D| 3#1#1#;1#4#4;5#1#4;|E|F|0|5|1|4
AE|B1|CC|DE| |EX|FF|0|||
AR|BE|CA|D1| 5#6#3#;4#3#4;|ED|G||5|6|3
AR|BE|CA|D1| 5#6#3#;4#3#4;|ED|G||4|3|4


Answered By - Ed Morton
Answer Checked By - Gilberto Lyons (WPSolving Admin)