Extract the letter from string

Hi,

Pl help me.

User is entering the values for the given input

Enter keys: secret1 secret2 secret3

can i extract the last digit of each values in the keys..
here for ex. 1 2 3

can we get this using shell script?

$ echo "secret1 secret2 serect3" |  awk '{gsub(/[a-z]/,""); print $0}'
1 2 3
read secrets

for i in $secrets
do
        str=$str" "$(echo $i | sed 's/.*\([0-9]$\)/\1/')
done

echo $str

Hi,

Thanks for the reply.

But am getting error...

echo "secret1 secret2 serect3" | awk '{gsub(/[a-z]/,""); print $0}'
awk: syntax error near line 1
awk: illegal statement near line 1

Try using gawk or nawk instead of awk. You may have to install them and I would recommend doing that if you're able.

or

use sed

echo "secret1 secret2 secret3" | sed 's/[a-z]//g'

i want to get the last digit.. it may contain letters also instead number..

your command works only to extract the numbers.. but i did not want this.

Pl help

Please provide a better example of input and output that you are looking for.

try this :

#!/bin/bash
read -p "Enter your words : "
for I in $REPLY
do
    let L=${#I}-1
    echo ${I:$L:1}
done
$ echo "secret1 secret2 serect3" |  awk 'BEGIN {RS=" "; ORS=" "} {key=substr($1,length($1)); print key}'

This should return whatever is in the last space of each string...

here, the great advantage of awk is that the first index in a string is 1 (0 in bash).:wink:

echo "secret1 secret2 secret3" | sed 's/\w*\(\w\)/\1/g'

---------- Post updated at 23:01 ---------- Previous update was at 22:43 ----------

secrets="secret1 secret2 secret3" 
for i in $secrets; do
  echo ${i#${i%?}}
done

Can you explain the w's for me? :confused:

Hi,

\w matches any "word" character. A "word" character is any letter or digit or the underscore character.

for example,

Enter the names: Test hai hello

I need the last digits of all the inputs..
here " tio " [last digits of Test hai hello]

Hope, you can understand my req. Thanks for your help

Hope this works...

$echo "Test hai hello" | sed 's/[^ ]\+\(.\)\( \|$\)/\1/g'
tio

You probably mean last character, since I do not see any digits in your example

names="Test hai hello"
for i in $names; do
  printf ${i#${i%?}}
done
echo
str="secret1 secret2 secret3"
set -- $str
echo ${@##*[a-z]}

OK

#!/bin/bash
read -p "Enter your words : "
for I in $REPLY
do
    let L=${#I}-1
    echo -n ${I:$L:1}
done

Thanks. This works..

Hi All,

The below script is working fine.
read names
for i in $names; do
printf ${i#${i%?}}
done
echo

May i know, what is the meaning for the "printf ${i#${i%?}}" statement and how it works?