Search code examples
stringawklinematching

How to print the value in third column of a line which comes after a line which, contains a specific string using AWK to a different file?


I have an output which contains something like this in the middle.

  Stopping criterion = max iterations
  Energy initial, next-to-last, final = 
        -83909.5503696     -86748.8150981     -86748.8512012

What I am trying to do is to print out the last value(3rd column) in line after the line which contains the string "Energy" to a different file. and I have to print out these values from 100 different files. currently I have been trying with this line which only looks at a single file.

awk -F: '/Energy/ { getline; print $0 }' inputfile > outputfile

but this gives output like:

       -83909.5503696     -86748.8150981     -86748.8512012

Update - With the help of a suggestion below I was able to output the value to a file. but as it reads through different files it overwrites the final output file and prints out value of the final file that it read. What I tried was this,

#SBATCH --array=1-100

num=$SLURM_ARRAY_TASK_ID..
fold=$(printf '%03d' $num)

cd $main_path/surf_$fold
awk 'f{print $3; f=0} /Energy/{f=1}' inputfile > outputfile

Solution

  • This would not be an appropriate job for getline, see http://awk.freeshell.org/AllAboutGetline, and idk why you're setting FS to : with -F: when your fields are space-separated as awk assumes by default.

    Here's how to do what I think you're trying to do with 1 call to awk:

    awk 'f{print $3; f=0} /Energy/{f=1}' "$main_path/surf_"*"/inputfile > outputfile