Search file for string and store last result to variable

Hi,

I'm trying to search a text file for a string: "energy(sigma->0)=". To do so, I executed the grep command, which returned many matches, for example:

  energy without entropy =     -112.16486170  energy(sigma->0) =     -112.16520778
  energy without entropy =     -112.16488936  energy(sigma->0) =     -112.16522827
  energy  without entropy=     -112.164889  energy(sigma->0) =     -112.165228

What I want to do is store the grep results to a variable (var1), then get the very last number in the very last string result (the last number in var1), and store it to a second variable (var2) for later use in bash.

Alternatively, if there is a better command than grep that can automatically return only the last search hit in a given file, that would be even better.

Any assistance would be greatly appreciated!

gwr

var1=$(grep "energy(sigma->0)=" text.file)
var2=${var1##*= }
1 Like

Perfect, works a treat! Cheers Chubler_XL.

var=$(grep "energy(sigma->0)=" file | tail -1)
awk '/energy\(sigma->0\) =/ {a=$NF}END{print a}' text.file

-112.165228
while read line
do
  case $line in
    *"sigma->0"*) var=${line##* }
  esac
done < infile
echo $var