Bash: Match a word in a string and return the word preceding it

The following shows how to match a word in a string and return previous word.

The following will return “word1” base on “=” as a search term

sed:

echo "bla bla word word1 = string1 string2" | sed -e 's/.* \([^ ]*\) =.*/\1/g'

perl:

echo "bla bla word word1 = string1 string2" | perl -n -e '/\s([^\s]+)\s=/; print $1;'