extract a word from text file name

Hi i want to extract the word present before .txt in the text file.

For example,

Sample_ab_a.txt ----------> i need 'a'
Sample_abc_b.txt -----------> i need 'b'

Can anyone help me in getting the word extracted

STR="Sample_ab_a.txt"
OLDIFS="$IFS"; IFS="_."
        set -- $STR # STR must not be quoted!
IFS="$OLDIFS"

while [ $# -gt 2 ] ; do shift ; done

echo "name is $1"
echo "Sample_ab_b.txt" | nawk -F"[_.]" '{print $(NF-1)}'
echo "Sample_ab_a.txt" | sed 's|.*\(.\)\.txt|\1|' 
a

echo "Sample_abc_b.txt" | sed 's|.*\(.\)\.txt|\1|' 
b

Thank u so much for all :slight_smile:

$echo Sample_ab_a.txt  | sed   s/.*_// | sed s/\.txt//
a