awk insert columns and printing on single line

Viewed 275

I am trying to use AWK to process a comma seperated text file and insert new columns. I want to split the contents of the second column into three parts and insert three columns after column B in a new text file.

insert.txt - my data

column A, name|ID1234 @ tag1, column C, column D

Output I am trying produce

column A, name|ID1234 @ tag1, name, ID1234, tag1, column C, column D

Code I have tried

#!/bin/awk

BEGIN {
   FS=","
  OFS=","
}
{
#  Split Column B - twice
   split($2,a,"|")   #a[1] a[2] seperated by |
   split(a[2],b,"@") #b[1] b[2] seperated by @    

   print $1,$2,a[1],b[1],b[2]; 
   {for(i=3;i<=NF;++i) printf $i}
}

awk -f insert.awk insert.txt > output.txt

How do I format the output to all be on a single line, comma separated with the inserted columns?

Is it possible during output to trim the white space at the begin and end of each column?

Thanks Joshua

3 Answers

You may use this solution in any version of awk:

awk 'BEGIN {FS=OFS=", "}
{v2 = $2; gsub(/ *[|@] */, OFS, v2); $2 = $2 OFS v2} 1' file

column A, name|ID1234 @ tag1, name, ID1234, tag1, column C, column D

We split each record using field separator ", " then replace | and @ with same field separator in the stores value of $2 which is variable v2. Then we append this changed value of v2 in $2 after OFS and finally print full record.

Another possibility with awk can be

awk 'BEGIN {FS=OFS=", "}{split($2,a,/[ |]/);print $1, $2, a[1], a[2], a[4], $3, $4}' file
column A, name|ID1234 @ tag1, name, ID1234, tag1, column C, column D

using split() we split up $2 field name|ID1234 @ tag1 into pieces saved in a array. Then we print three of them a[1] a[2] a[4] between $2 and $3 fields.

The separator for split() can be a regular expression, not just a single character: /[ |]/

With your shown samples, please try following awk code. Written and tested with GNU awk.

awk '
match($0,/^[^,]*,[^,]*,/){
  val1=$3
  sub(/\|/,", ",val1)
  val2=val3=substr($0,RSTART,RLENGTH)
  sub(/.*@ /,"",val3)
  print val2,  val1 ", " val3 substr($0,RSTART+RLENGTH)
}
'  Input_file
Related