Search code examples
csvsedawkrow

(sed/awk) Extract values from text to csv file - even/odd lines pattern


I need to export some numeric values from a given ASCII text file and export it in a specific formatted csv file. The input file has got the even / odd line pattern:

 SCF Done:  E(UHF) =  -216.432419652     A.U. after   12 cycles
 CCSD(T)= -0.21667965032D+03
 SCF Done:  E(UHF) =  -213.594303492     A.U. after   10 cycles
 CCSD(T)= -0.21379841974D+03
 SCF Done:  E(UHF) =  -2.86120139864     A.U. after    6 cycles
 CCSD(T)= -0.29007031339D+01
 and so on

I need the odd line value in the 5th column and the even line 2nd column value. They should be printed in a semicolon seperated csv file, with 10 values in each row. So the output should look like

-216.432419652;-0.21667965032D+03;-213.594303492;-0.21379841974D+03;-2.86120139864;-0.29007031339D+01; ...linebreak after 5 pairs of values

I started with awk '{print $5}' and awk '{print $2}', however I was not successful in creating a pattern that just acts on even/odd lines.

A simple way to do that?


Solution

  • The following script doesn't use a lot of the great power of awk, but will do the job for you and is hopefully understandable:

    NR % 2 { printf "%s;", $5 }
    NR % 2 == 0 { printf "%s;", $2 }
    NR % 10 == 0 { print "" }
    END { print "" }
    

    Usage (save the above as script.awk):

    awk -f script.awk input.txt