Unix Shell - substring using ksh

This is Interesting: Free IT Magazines  
Home > Archive > Unix Shell > November 2006 > substring using ksh





You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

Author substring using ksh
Tim B

2006-11-27, 1:29 am

In a ksh 88 script , I want to test a variable to see if its value contains
a certain substring. Can this be done with grep? If so, does anyone have an
example?


Chris F.A. Johnson

2006-11-27, 1:29 am

On 2006-11-27, Tim B wrote:
> In a ksh 88 script , I want to test a variable to see if its value contains
> a certain substring. Can this be done with grep? If so, does anyone have an
> example?


You don't need grep, or any other external command. The following
checks whether $substring is contained in $string in all
Bourne-type shells (sh, ksh, bash, ash, ...):

case $string in
*"$substring"*) echo Contains ;;
*) echo Does not contain ;;
esac

--
Chris F.A. Johnson, author <http://cfaj.freeshell.org/shell>
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
===== My code in this post, if any, assumes the POSIX locale
===== and is released under the GNU General Public Licence
Dan Mercer

2006-11-27, 7:23 pm

Use a conditional expression:

if [[ $string = *somesubstring* ]]; then

Extended globbing adds enormous power to the search.

More portably, use case:

case $string in
*somesubstring*) do_something;;
esac

Dan Mercer

"Tim B" <nospam@someisp.ca> wrote in message news:k_uah.380298$5R2.229395@pd7urf3no...
: In a ksh 88 script , I want to test a variable to see if its value contains
: a certain substring. Can this be done with grep? If so, does anyone have an
: example?
:
:


Tim B

2006-11-28, 1:32 am


"Dan Mercer" <damercer@comcast.net> wrote in message
news:U9CdnbY2Xa2f5fbYnZ2dnUVZ_tSdnZ2d@co
mcast.com...
> Use a conditional expression:
>
> if [[ $string = *somesubstring* ]]; then
>
> Extended globbing adds enormous power to the search.
>
> More portably, use case:
>
> case $string in
> *somesubstring*) do_something;;
> esac
>
> Dan Mercer
>
> "Tim B" <nospam@someisp.ca> wrote in message

news:k_uah.380298$5R2.229395@pd7urf3no...
> : In a ksh 88 script , I want to test a variable to see if its value

contains
> : a certain substring. Can this be done with grep? If so, does anyone have

an
> : example?
> :


Thanks for the replies, Chris and Dan


Sponsored Links






Free braindumps | Software forum | Database administration forum

Copyright 2003 - 2008 webservertalk.com