5

I have to extract a substring using ksh88. (BTW the simple way of finding the version of ksh $KSH_VERSION is not working for me. I had to use

 [ "`echo "\c" | grep c`" ] && echo ksh93 || echo ksh88 

I tried using the command echo ${stringvariable : 2: 2} But it says bad substitution. I am new to the Unix world. This is what I did to get the result:

I've logged into Unix using PUTTY and typed the above command. I also tried first ksh command, then my command but still no success. Is there anything I am doing wrong?

Also if I want the substring till end starting from position 2 how to do that?

2 Answers 2

7

Whitespace is significant in the shell. You should use

$ stringvariable="foobar" $ echo ${stringvariable:2:2} ob 

Note: This works on ksh93, It won't work with ksh88.

If your words are space separated, you can use set:

$ stringvariable="foo bar baz zap" $ set -- $stringvariable $ echo $3 baz 

This should always be preferred over useless forks of cut. Using cut to get at characters in a string is the programming equivalent of using a 40 ton truck to buy and transport a piece of cube sugar.

Sign up to request clarification or add additional context in comments.

5 Comments

doesnt work :( same error. bad substitution. The second option works well. But could you explain what does the second line "set --" does ?
@user Yes it does work, and I provided the evidence. If it doesn't work for you, you are not using a current ksh. The set command sets the positional parameters. The stringvariable is split at the characters in IFS (usually blank, newline, tab) and then assigned to $1 etc.
thanks @Jens. as mentioned in the question i have ksh88. Even i dont know why its not working for me.
@user1016198 That explains it. It was ksh93 which introduced substring extraction, see kornshell.com/doc/ksh93.html
@mlwacosmos Is your shell a ksh93? It won't work with ksh88.
4

I found another solution which worked for me. Could not find why the solution in the question itself is not working.

Here is what worked for me:

str1="get word from this-text" 

get second word. -d is the delimiter(here space)

str2=`echo $str1 | cut -d" " -f 2` echo $str2 word 

get 3 chars starting at 5th

str2=`echo $str1 | cut -b 5-3` echo $str2 wor 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.