I have a file in the following format:

Original format


The above is an example of the first two lines of the contents of the file. Every line following these two first lines is identical in format to the example provided. The first space is the name of the file (which can be of varying length depending on the name of the original, e.g. ARX, HOXA13, PABPN1, ARX_PA1, etc.) that was processed which is followed by a chain of characters separated from the name by a comma.

What I need is to learn how to turn this original format into a csv format with the title in quotes and every character following the name in quotes and separated from one another by a comma with no trailing commas at the end of the lines.

Sample output:

"ARX_10/model2","C","E","E","C","C","C","C","C","H","H","H", ...
"ARX_10/model3","C","T","T","S","C","C","C","T","T","T","T", ...

Thanks for your help.


4 Answers 4


Based upon the recommendation from @Phillipos:

sed 'h;s/.*,//;s/./,"&"/g;x;G;s/,.*\n/"/;s/^/"/' inp.csv 


Divide the pattern space into two parts and operate on them separately then bring them together.

perl -lpe '$_ = q["] . join(q[","], unpack sprintf "A%dx(A)*", index $_, ",") . q["]' inp.csv

Brief Explanation:

° Construct the unpacking format for the input line by finding the location position of the comma, skip the comma from unpack, remaining are unpacked a char each. Then joined with the string ",", finally all enclosed in double quotes. 
  • +1. Just drop that nasty looping sed solution and explain the second one. Maybe simplify as 'h;s/.*,//;s/./,"&"/g;x;G;s/,.*\n/"/;s/^/"/'
    – Philippos
    Commented Jul 31, 2019 at 9:24

This may be what you're looking for:

$ awk -F, -v OFS= '{$1="\""$1"\""; gsub(/./,",\"&\"",$2)} 1' file

The above was run against this input:

$ cat file

IFS=, ; while read label string; do echo "\"$label\",$(echo $string| sed -e 's/\(.\)/\"\1\",/g' -e 's/,$//') "; done < inputfile

  • Split into label and string to transform by setting the IFS to ','
  • Read line by line from the line
  • let sed replace "." ( = every single char) with '"char",'...
  • and delete the ',' at the end of the line

Tested with below command and it worked fine


for i in `cat o.txt`; do j=`echo $i | awk -F "," '{print $1}'`; echo $i | awk -F "," '{print $2}'| sed 's/\(.\)/"&",/g'| awk -v j="$j" '{print j","$0}'| sed 's/^/"/g'| sed 's/,/"&/1'| sed 's/,$//g'; done

where o.txt==> filename

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .