Search code examples
bashawksedgrepcut

Find a line of a file, extract part of it and replace in the same place in Bash


I have a large file with the following content (this is an extract of it):

Total execution time (hh:mm:ss.ms): 00:00:8,4880 (8488 mseconds)
Error  0.00044
Stage 1 execution time (hh:mm:ss.ms): 00:00:7,0430 (7043 mseconds)
Stage 2 execution time (hh:mm:ss.ms): 00:00:1,4450 (1445 mseconds)
Total execution time (hh:mm:ss.ms): 00:00:0,0170 (17 mseconds)
Number of variables   6

Those lines could be more than one time and with different values. I would like to replace for the mseconds value. So, the expected output is:

8488
Error  0.00044
7043
1445
17
Number of variables   6

I've tried this but I don't know how can I replace the extracted value in the line:

grep "Total execution time (hh:mm:ss.ms):" file.txt | cut -d " " -f6 | cut -d "(" -f2

And I also was thinking doing this for each case (Total, Stage 1 and Stage 2), but if there is something more practical I would be very grateful.


Solution

  • It would be easier using sed (I use GNU sed, to be specific) to achieve the result:

    sed -E '/execution time/s/.*\(([0-9]*) mseconds\)/\1/'
    

    Keep only the digit part \(([0-9]*) mseconds\) in lines with pattern execution time. The ([0-9]*) are used as backreference in order to output the desired number by using \1, and \( and \) mean literal parenthesis.