Finding the position of a sub string within a strong
Ray Parrish
crp at cmc.net
Sun Nov 29 21:02:51 UTC 2009
James Michael Fultz wrote:
> * Ray Parrish <crp at cmc.net> [2009-11-29 06:09 -0800]:
>
>> I am starting to get a grasp on what can be done with regular
>> expressions, and I now know how to extract a sub string from within
>> another string if I know it's offset, and length.
>>
>
> Using regular expressions allows for matching patterns where you may not
> know exact offset and length.
>
>
>> The thing I haven't discovered during all of this reading is a way to
>> return the position of a substring within another string.
>>
>> How would I return the position of the sub string "zat" in the string
>> "abczat1256"?
>>
>
> $ echo "abczat1256" | awk '{print index($0,"zat"}'
>
>
>> I know how to get the length of a string now, but not how to search
>> within it yet. I have thought of a cludge which involves stripping
>> character at a time from the front of the string into an array, but why
>> re-invent the wheel when I'm sure there is already a simpler way to do this.
>>
>
> You can perform some basic string manipulations in the shell itself,
> particularly using Bash (or Ksh or Zsh). You can perform more complex
> string manipulations with sed and AWK.
>
> sed is good for string replacements within a line. It's not so good for
> multi-line string manipulations. You can do more than string
> replacement with sed, but it gets complicated quickly.
>
> AWK can perform all sorts of text manipulations as well as arithematic
> and is preferable sed for multi-line operations.
>
Hello,
While reading i found the following method, which seems reasonable to me.
Position=`expr index "$String" "$SubString"`
That returns the starting position of SubString within String, and it
even works! I'm beginning to see the possibilities as I learn more about
bash.
Thanks for the awk pointer, but this method assigns directly to a
variable, which is what I was looking for.
Later, Ray Parrish
--
The Future of Technology.
http://www.rayslinks.com/The%20Future%20of%20Technology.html
Ray's Links, a variety of links to usefull things, and articles by Ray.
http://www.rayslinks.com
Writings of "The" Schizophrenic, what it's like to be a schizo, and other
things, including my poetry.
http://www.writingsoftheschizophrenic.com
More information about the ubuntu-users
mailing list