Languages and Scripting
Showing results for 
Search instead for 
Do you mean 

How to extract char from string in $variable?

SOLVED
Go to Solution
Advisor

How to extract char from string in $variable?

Hi,

How do i extract certain characters from a string stored in a $variable?

For example:

set text = "01L"

i want to extract and store "01" only into another $variable. Thanks!
5 REPLIES
Honored Contributor Honored Contributor

Re: How to extract char from string in $variable?

try
echo $text|cut -c 1,2
or
echo $text|cut -c 1-2 (to any digits you want to cut)
Honored Contributor Honored Contributor

Re: How to extract char from string in $variable?

say your assign the value to $valiable as
export variable="01L"
var1=`echo $variable|cut -c 1,2`
echo $var1
Advisor

Re: How to extract char from string in $variable?

Thanks Raj!
I've got it!
Exalted Contributor Exalted Contributor

Re: How to extract char from string in $variable?

Highlighted
Honored Contributor Honored Contributor

Re: How to extract char from string in $variable?


Andrew,

I'm glad you found a solution.
However, it involves a fork of a utility where it seems that a native shell command can do the trick.
For onesies-twosies it does not matter, for commands executed in a tight loop it can make a critical difference in execution performance.

The shell has several editing operations.
In your case i woudl consider 'tail end pattern deletion'

For example:

# text="01L"
# other=${text%[A-Z]}
# echo $other
01

from "man ksh"
:
${parameter%pattern}
:
If the shell pattern matches the end of the value of parameter, the value of parameter with the matched part is deleted; otherwise substitute the value of parameter. In the former, the smallest matching pattern is deleted; in the latter, the largest matching pattern is deleted.


hth,
Hein.