Simpler Navigation for Servers and Operating Systems
Completed: a much simpler Servers and Operating Systems section of the Community. We combined many of the older boards, so you won't have to click through so many levels to get at the information you need. Check the consolidated boards here as many sub-forums are now single boards.
Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

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

SOLVED
Go to solution
Patrick Ware_1
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
Bill Hassell
Honored Contributor
Solution

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


Bill Hassell, sysadmin
Patrick Ware_1
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..
Steven Schweda
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
James R. Ferguson
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...
Bill Hassell
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.


Bill Hassell, sysadmin
TTr
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`