Ubuntu – How to grep two numbers from the same line at different places using bash

bashcommand linegreptext processing

I want to grep 2 numbers from the same line in the example below:

// ExampleFile.txt
solver.cpp:229] Iteration 2000, loss = 0.305721
solver.cpp:245]     Train net output #0: accuracy = 0.926112
solver.cpp:245]     Train net output #1: accuracy = 0.723957
solver.cpp:245]     Train net output #2: accuracy = 0.599623
sgd_solver.cpp:106] Iteration 2000, lr = 0.000227383
solver.cpp:229] Iteration 2020, loss = 0.294722
solver.cpp:245]     Train net output #0: accuracy = 0.855208
solver.cpp:245]     Train net output #1: accuracy = 0.71616
solver.cpp:245]     Train net output #2: accuracy = 0.619429

I need the number to the right of "solver.cpp:229] Iteration " and to the right of ", loss = ". I need to get both numbers at the same time such that my resulting file looks like this:

// ResultFile.txt
2000 0.305721
2020 0.294722

I only know how to get one of the numbers using grep like this

grep ", loss = " ExampleFile.txt | sed -e "s/.* //" > ResultFile.txt

Does anyone know how to get the second number simultaneously?

Best Answer

One possible way...

% grep 'solver.cpp:229' ExampleFile.txt | cut -d ' ' -f 3,6 | tr -d ','
2000 0.305721
2020 0.294722