Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

Pulling the first and last character/number from a string.

SOLVED
Go to Solution
Super Advisor

Pulling the first and last character/number from a string.

Let's say I have a word "foobar23" in a file, and I want to pull the first "f" and last "3" character out of the world, how would I accomplish that?

# cat file
foobar23

I want the output to be:

f3
6 REPLIES
Highlighted
Honored Contributor Honored Contributor

Re: Pulling the first and last character/number from a string.

Lots of choices depending on the rules. The general way is to use cut as in:

cat file | while read TEXT
do
LEN=${#TEXT}
print $(print "$TEXT" | cut -c1,$LEN)
done
Super Advisor

Re: Pulling the first and last character/number from a string.

Thanks! That worked great!
Now I am trying to figure out how to make that all a variable that I can embed into a script..
Honored Contributor Honored Contributor

Re: Pulling the first and last character/number from a string.

"man sh".

td192> echo foobar23 | \
sed -e 's/^\(.\).*\(.\)$/\1\2/'
f3

td192> x=` echo foobar23 | \
sed -e 's/^\(.\).*\(.\)$/\1\2/' `
td192> echo $x
f3

Or, the trendy, new way:

td192> x=$(echo foobar23 | sed -e 's/^\(.\).*\(.\)$/\1\2/')
td192> echo $x
f3
Acclaimed Contributor Acclaimed Contributor

Re: Pulling the first and last character/number from a string.

Hi Patrick:

# echo "foobar23"|perl -nle 'print substr($_,0,1),substr($_,-1)'
f3

# perl -nle 'print substr($_,0,1),substr($_,-1)' file
f3

...in in your shell script:

# THING=$(perl -nle 'print substr($_,0,1),substr($_,-1)' file)
# echo ${THING}
f3

...JRF...
Honored Contributor Honored Contributor

Re: Pulling the first and last character/number from a string.

> ...variable in the script...

cat file | while read TEXT
do
LEN=${#TEXT}
MYVAR="$(print "$TEXT" | cut -c1,$LEN)"

...more script stuff...
print "First-Last=$MYVAR"

done

The main line is the: MYVAR="$(...)" where the result of the cut command is assigned to a variable called MYVAR. Be sure to use " because there may be a leading and/or trailing space in your file. Then test or use $MYVAR with "$MYVAR" to preserve and special characters.
Honored Contributor Honored Contributor

Re: Pulling the first and last character/number from a string.

How about this

WORD=`cat filename`
FIRSTCHAR=`echo $WORD | cut -c 1`
LASTCHAR=`echo $WORD | rev | cut -c 1`
I do not reply to forumers who 1) consistently don't assign points, 2) ask for step-by-step instructions for a topic but appear to have no IT experience and make no effort to learn. Some exceptions for newcomers and special topics.