Question

I have a text file,in which data is of the form:

Number of Iterations: 150
Average time is 45 ms
Average time for collisions is 50 ms
Total time is 95 ms
....

There are multiple files of this kind. I have to read all these files and make a csv file which will contain entries of the form:

150,45,50,95
200,40,60,100 
...
...

where each row corresponds to one txt file.
I am writing a bash script to generate the CSV file from this data.
I want to read only the numbers from the text file.
For the first line I tried to use

    IFS =": " read w1 w2

But it splits the line by using space also as delimiter along with ':'
When I used

    IFS=":" 

An additional space was printed in front of 150 which I dont want.
How do I do this?
Also in the second line I want to use "is " as a delimiter. Is it permitted?
Thanks

Was it helpful?

Solution

You can use this awk:

cat file
Number of Iterations: 150
Average time is 45 ms
Average time for collisions is 50 ms
Total time is 95 ms
Number of Iterations: 200
Average time is 40 ms
Average time for collisions is 60 ms
Total time is 100 ms

awk '/^Total/{p=1} {gsub(/[^0-9]+/, ""); a[++i]=$0}
     p{print a[1], a[2], a[3], a[4]; p=0; delete a; i=0}' OFS=, file
150,45,50,95
200,40,60,100
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top