If the last column is "R", then ... Is this possible? In unix

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

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

Is it possible?

+4
source share
4 answers

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 
+1
source

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" $ 
+9
source

The condition may be:

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

No need for an external language like awk .

+3
source

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 
+2
source

Source: https://habr.com/ru/post/1486009/


All Articles