Operating System - HP-UX
1755099 Members
1466 Online
108829 Solutions
New Discussion юеВ

Re: Get 1st and LAST char

 
SOLVED
Go to solution
Keith Floyd
Advisor

Get 1st and LAST char

Hi

I am trying to get the first and last char from a string (variable length)

Does anyone know the way to do it ??

Thanks

Keith
3 REPLIES 3
James R. Ferguson
Acclaimed Contributor
Solution

Re: Get 1st and LAST char

Keith:

To get the first and the last character of a string, use the substr and length functions of awk.

# S=abcdef
# F=`echo $S|awk '{print substr($0,1,1)}'`
# L=`echo $S|awk '{print substr($0,length($0),1)}'`

where S is your variable string,
and F is the first character returned,
and L is the last character of the string.

...JRF...
wyan lowe
Frequent Advisor

Re: Get 1st and LAST char

could also try sed

s=abcdef
f=echo "$s" | sed -n "s/^(.).*/1/p"
l=echo "$s" | sed -n "s/.*(.)$/1/p"


could try using [a-zA-Z] instead of just "." if matching for a letter
"." matches any single character - except newline, I think...
curt larson
Frequent Advisor

Re: Get 1st and LAST char

you could use a more modern shell version then the '88 version that HP supplies for /usr/bin/sh and ksh. Such as:

#!/usr/dt/bin/dtksh
string=abcdef

F=${string:0:1}
L=${string:$(( ${#string} - 1 )):1}

and if you'd prefer just calling awk or sed once

echo $string |
awk '{
print substr($0,1,1) " " substr($0,length($0),1);
}' |
read F L

echo $string |
sed -n "s/^\(.\)*\(.\)$/\1 \2/p" |
read F L
nobody else has this problem