Operating System - Linux
1752772 Members
5011 Online
108789 Solutions
New Discussion юеВ

Re: 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 5
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.