So I have a big file containing the values of a matrix with the folowing format:

(0,0) 0.6666
(0,1) 0.0000
(0,2) 1.3333

And I want to convert it to:

0 0 0.6666e+00
0 1 0.0000e+00
0 2 1.3333e+00

I can do this with the following script:


while read coord val; do
   printf "%s" "${coord//,/ }" | awk -F '[()]' '{printf "%s",$(NF-1)}'  
   printf " %8.3e\n" "$val"
done < "$input"

But this is extremely slow for my case ( 9409 lines) How can I do this faster?


Here's a slightly different awk approach. This should be faster than using sub and gsub1:

awk -F'[(,)]' '{printf "%s %s %8.3e\n",$2,$3,$4}' file

1I tested it on a file with 5000000 lines and it was ~2seconds faster than the gsub/sub approach. Not a great difference but it might be important for huge files.

  • Yes thats faster, and it gives more control. Maybe I need to transform it to 0-base arrays to 1-base array and I can do it with ++$2, ++$3. Thanks! – Msegade Feb 26 '16 at 13:30

It will be faster if you let awk do it alone:

awk '
  gsub("[()]", "", $1)
  sub(",", " ", $1)
  $2 = sprintf("%8.3e", $2)
}' <file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.