Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix row to column format with string prefix and post fix

Tags:

shell

unix

I have the requirement to convert row string data to column format and pre/postfix specific strings. The data string in file has 4 major fixed columns (separated by ";") and each column is further divided in two sections (separated by ":").

E.g.

Source data file:

A100:T100;B100:T200;A200:T300;B200:T400

Output from file should be:

TABa:BatchID=A100:TagId=T100:ProcId=1
TABb:BatchID=B100:TagId=T200:ProcId=2
TABc:BatchID=A200:TagId=T300:ProcId=3
TABd:BatchID=B200:TagId=T400:ProcId=4

Meanwhile I am trying with following code:

String="A100:T100;B100:T200;A200:T300;B200:T400"

> File.txt
for deploy in $(echo $String | tr ";" "\n")
do
   echo $deploy >> File.txt
done

cat File.txt | awk 'BEGIN { FS=":"; OFS=":" } NR==1{ print "TABa:BatchID="$1,$2 } NR==2{ print "TABb:BatchID="$1,$2 }'
like image 651
Bhupinder Avatar asked Dec 05 '25 07:12

Bhupinder


1 Answers

printf handles this:

$ awk -F: '{sub(/\n/,""); printf "TAB%c:BatchID=%s:TagId=%s:ProcId=%i\n",(NR+96),$1,$2,NR }' RS=';' File.txt
TABa:BatchID=A100:TagId=T100:ProcId=1
TABb:BatchID=B100:TagId=T200:ProcId=2
TABc:BatchID=A200:TagId=T300:ProcId=3
TABd:BatchID=B200:TagId=T400:ProcId=4

How it works

  • -F:

    This sets the field separator to a colon: :.

  • sub(/\n/,"")

    This removes newline characters.

  • printf "TAB%c:BatchID=%s:TagId=%s:ProcId=%i\n",(NR+96),$1,$2,NR

    This does all the work. It makes use of the record number, NR, and the first and second fields and prints the output that you want.

  • RS=';'

    This tells awk to use a semicolon, ;, as the record separator.

like image 72
John1024 Avatar answered Dec 08 '25 00:12

John1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!