1833789 Members
2547 Online
110063 Solutions
New Discussion

who do I do a substr ?

 
SOLVED
Go to solution
Kamran Hussain
Occasional Advisor

who do I do a substr ?

variableX can be tad4 or tad

I always want the first 3 characters, so the result should always be "tad".

How do I get the first 3 characters from variableX ?
5 REPLIES 5
Jeff Schussele
Honored Contributor
Solution

Re: who do I do a substr ?

Hi Kamran,

Try this

echo $X | cut -c 1-3

This will return the first three characters of the variable X.

HTH,
Jeff
PERSEVERANCE -- Remember, whatever does not kill you only makes you stronger!
Kamran Hussain
Occasional Advisor

Re: who do I do a substr ?

Thank you.

I knew it was an easy one; I was having the worst luck with awk:

works here:
df -k /u100 | sed '1d' | awk '{print $5}' | awk '{printf "%02d\n", $1}'

but not here !:
(given: x=tad4)
echo $X | awk '{printf "%03d\n", $1}'

Can you shed some light on the above 2 -thanks.
curt larson_1
Honored Contributor

Re: who do I do a substr ?

with awk you should be using the %s as the conversion type in the printf statement, printf("%3s\n",$1); or using substr, printf("%s\n",substr($0,1,3);

or you could use sed, sed 's/\(...\).*/\1/'
H.Merijn Brand (procura
Honored Contributor

Re: who do I do a substr ?

You can also use 'di' from http://www.gentoo.com/di/
Precompiled version available for HP-UX 11.00 and 10.20 on my ITRC site: https://www.beepz.com/personal/merijn/#Downloads
di has an option to spit out it's info in an easy to parse format.
Once used to di you never want to use df or dbf anymore
Enjoy, Have FUN! H.Merijn
Scott Williams_5
Frequent Advisor

Re: who do I do a substr ?

If you have a variable length string, you can also use the % operator to remove a substring from the right end of a string.

>a="tadf"
>b="${a%?}"
>print $a
tadf
>print $b
tad





Scott Williams