Simpler Navigation coming for Servers and Operating Systems
Coming soon: a much simpler Servers and Operating Systems section of the Community. We will combine many of the older boards, and you won't have to click through so many levels to get at the information you need. If you are looking for an older board and do not find it, check the consolidated boards, as the posts are still there.
Languages and Scripting
cancel
Showing results for 
Search instead for 
Did you mean: 

How to extract char from string in $variable?

SOLVED
Go to solution
Andrew Yip
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
Highlighted
Rajeev Shukla
Honored Contributor
Solution

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)
Rajeev Shukla
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
Andrew Yip
Advisor

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

Thanks Raj!
I've got it!
Steven E. Protter
Exalted Contributor

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

Hein van den Heuvel
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.