21

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?

3 Answers 3

31

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
0
6

If I correctly understand the question you want to get only values after =, and store the these values in separate files, based on second field(?). If I'm right try something like this:

$ awk -F'[ =]' '{print $6>"file_"$2".txt"}' file

The result:

$ ls -1
  file_leftWallPhi.txt
  file_leftWallUSf.txt
  file_leftWallrhoPhi.txt
  file_leftWallrhoUSf.txt
  file_loweWallrhoPhi.txt
  file_loweWallrhoUSf.txt
  file_lowerWallPhi.txt
  file_lowerWallUSf.txt

$ cat  file_leftWallPhi.txt
  5.12623e-12
1
  • @KasiyA I cannot reproduce your problem with GNU awk 4.0.2. The command from my answer works also with -c option (compatibility mode with traditional UNIX awk where GNU extensions are disabled). Please be sure you have updated input file as the original question was edited and empty lines deleted.
    – jimmij
    Commented Nov 11, 2014 at 11:38
1

You can do it by sed

sed -E 's/^.* (\S+)\s*:.*=(\S+)/echo "\2" > "\1".txt/' file | bash

The script find out two pieces in line:

  1. between spaces and : and should contain some(more then 0) non-space symbols ;
  2. some(more then 0) non-space symbols after =;

and format from its in execution command which transfered through the pipe to bash

1
  • A much more versatile answer.
    – duanev
    Commented Aug 2, 2016 at 21:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .