This is extended question from


I'm new to shell. I've written a shell script a code with finds a sentence I want to subtract the value from that sentence. the sentence is as below

FINAL SINGLE POINT ENERGY       -39.022584378179

I want the numerical part, expr substr gives me unknown command error and actually the lenght of my numerical part may vary so I wanted to use awk something like:

awk -F" " '{ print $1 }' $line

can you guys help me

here's my code

while IFS= read -r line; do
  case $line in
      [ "$optimized" = 1 ] || continue
      final_energy=`echo $line | awk '{print $NF }'`
      echo "Found optimized final energy: $final_energy"
    "final energy")
done < input-s.out

the log file is a long file contains many FINAL SINGLE POINT ENERGY" and has to read only the last one which comes after hurray.

  • you should understand the use of final_energy=${line#*:} . In this colon (:) is used but in your input data line no colon is present. – Shravan Yadav Aug 19 '15 at 14:18
  • try this final_energy=echo $line | awk '{ print $NF }' – Shravan Yadav Aug 19 '15 at 14:21
  • ah, you're right it's a bug, I forgot to remove it – Raymond Ghaffarian Shirazi Aug 19 '15 at 14:21
  • @ShravanYadav it gives me "awk: can't open file FINAL" – Raymond Ghaffarian Shirazi Aug 19 '15 at 14:24
  • please add the ouput after running the script and also the error in it. – Shravan Yadav Aug 20 '15 at 3:57
$ awk '/HURRAY/ { ok = 1 } ok == 1 && /^FINAL SINGLE POINT ENERGY/ { printf("Found optimized final energy: %s\n", $NF) }' input-s.out

I think this does what your shell script is trying to do.

If it finds the string HURRAY somewhere, it sets ok to 1 (your optimized variable). If ok is 1 and it finds a line starting with the string FINAL SINGLE POINT ENERGY, it displays the message followed by the value in the last column of that same line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.