Extracting part of lines with specific pattern using awk or sed

awksedtext processing

I have a question regarding the awk/sed operators. I have a big file which has the following set of lines repeated

Expression loweWallrhoPhi :  sum=-6.97168e-09
Expression leftWallrhoPhi :  sum=6.97168e-09
Expression lowerWallPhi :  sum=-5.12623e-12
Expression leftWallPhi :  sum=5.12623e-12
Expression loweWallrhoUSf :  sum=-6.936e-09
Expression leftWallrhoUSf :  sum=6.97169e-09
Expression lowerWallUSf :  sum=-5.1e-12
Expression leftWallUSf :  sum=5.12624e-12

I want to extract the value after the keyword sum in each case into a separate file. Is it possible to do so at one go?

Best Answer

With grep:

grep -oP 'sum=\K.*' inpufile > outputfile

grep with -P(perl-regexp) parameter supports \K, which use to ignoring the previously matched characters.

With awk:

awk -F"=" '{ print $NF; }' inputfile > outputfile

in awk the variable NF represent the total number of fields in a current record/line which is point to the last field number too and so $NF is its value accordingly.

With sed:

sed 's/^.*sum=//' inpufile > outputfile

^.*=sum replace all characters(.*) between starting of line(^) and last characters(sum=) with whitespace char.

Result:

-6.97168e-09
6.97168e-09
-5.12623e-12
5.12623e-12
-6.936e-09
6.97169e-09
-5.1e-12
5.12624e-12

With cut:

cut -d'=' -f2 inputfile > outputfile

if you want save same values into a same file and each separately, with awk you can do:

awk -F"=" '{print $NF >($NF); }' inputfile > outputfile
Related Question