Question

I need to find the last column from a variable that contains some fields. I need to write something like:

    if [ #the last column = "R" ];
    then
    value=`echo "'$value'"`
    fi

Is it possible?

Was it helpful?

Solution 4

More universal code assuming separation by spaces:

case $var in
  (*\ R) printf "%s\n" "$var"
esac

Or:

if [ "${var##* }" = R ]; then
  printf "%s\n" "$var"
fi

OTHER TIPS

With awk you can try:

awk '$NF=="R"' <<< "$var"

Test:

$ var="this is a var with last as R"
$ awk '$NF=="R"' <<< "$var"
this is a var with last as R
$ var1="This should not be printed"
$ awk '$NF=="R"' <<< "$var1"
$

The condition can be:

if [[ $value == *' 'R ]]
then
    echo $value
fi

No need for an external language, like awk.

Using the =~ binary operator:

$ var="Some arbitrary string ending in R"
$ unset value
$ [[ "$var" =~ $'R$' ]] && value=${var}
$ echo $value
Some arbitrary string ending in R
$ var="Some arbitrary string ending in Q"
$ unset value
$ [[ "$var" =~ $'R$' ]] && value=${var}
$ echo $value
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top