1823240 Members
3439 Online
109648 Solutions
New Discussion юеВ

Re: String manipulation

 
dude70
Occasional Advisor

String manipulation

Hi

I have a string variable s="manipulate"

I want to extract from pos 2 to 5 . I should get a string "anip" what is the command in ksh.

Thanks.
8 REPLIES 8
Brian Markus
Valued Contributor

Re: String manipulation

#!/bin/sh
s="manipulate"
s1=`expr substr $s 2 4`
echo $s1


Enjoy.. :)

-Brian.
When a sys-admin say's maybe, they don't mean 'yes'!
Hein van den Heuvel
Honored Contributor

Re: String manipulation


Or:

echo "manipulate" | cut -b 2-5


Hein.
Mark Grant
Honored Contributor

Re: String manipulation

or my favourite (because it works with all shells)

s=`expr "manipulate" : "^.\(....\).*"`
Never preceed any demonstration with anything more predictive than "watch this"
RAC_1
Honored Contributor

Re: String manipulation


echo "manipulate" | cut -c2-5
There is no substitute to HARDWORK
Christian Gebhardt
Honored Contributor

Re: String manipulation

Hi
what's about
--------------------------
s=manipulate
echo $s | awk '{print substr($0,2,4)}'
---------------------------
works also with every shell

Chris
Elmar P. Kolkman
Honored Contributor

Re: String manipulation

echo $s | cut -c2-5
OR
echo $s | sed 's|^.\\(...\\).*$|\\1|'
Every problem has at least one solution. Only some solutions are harder to find.
dude70
Occasional Advisor

Re: String manipulation

Thank you all guys! It worked!
Rodney Hills
Honored Contributor

Re: String manipulation

Since you specified ksh, then the following will work for a fixed substring. The benefit of this is that it does not have to start a subshell to run another command (awk, expr, etc...).

s="manipulate"
typeset -L4 a="${s#??}"

s#?? will return "s" with the first 2 characters stripped. typeset -L4 will put that result into "a", but limit the size to 4 characters.

This technique doesn't work if the extract may be variable.

HTH

-- Rod Hills
There be dragons...