Re: How to extract char from string in $variable? (264 Views)
Reply
Advisor
Andrew Yip
Posts: 20
Registered: ‎11-29-2005
Message 1 of 6 (264 Views)
Accepted Solution

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!
Honored Contributor
Rajeev  Shukla
Posts: 1,402
Registered: ‎01-25-1999
Message 2 of 6 (264 Views)

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
Rajeev  Shukla
Posts: 1,402
Registered: ‎01-25-1999
Message 3 of 6 (264 Views)

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
Andrew Yip
Posts: 20
Registered: ‎11-29-2005
Message 4 of 6 (264 Views)

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

Thanks Raj!
I've got it!
Exalted Contributor
Steven E. Protter
Posts: 33,806
Registered: ‎08-15-2002
Message 5 of 6 (264 Views)

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

Shalom,

http://www.google.com/url?sa=t&ct=res&cd=2&url=http%3A%2F%2Fwww.dreamsyssoft.com%2Funix-shell-script...

http://www.google.com/url?sa=t&ct=res&cd=1&url=http%3A%2F%2Fwww.cactus.org%2F~dak%2Fshellscript.html...

Perhaps these links will help.

SEP
Steven E Protter
Owner of ISN Corporation
http://isnamerica.com
http://hpuxconsulting.com
Sponsor: http://hpux.ws
Twitter: http://twitter.com/hpuxlinux
Founder http://newdatacloud.com
Honored Contributor
Hein van den Heuvel
Posts: 6,588
Registered: ‎05-19-2003
Message 6 of 6 (264 Views)

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.
The opinions expressed above are the personal opinions of the authors, not of HP. By using this site, you accept the Terms of Use and Rules of Participation.