Finding the position of a sub string within a strong
James Michael Fultz
croooow at gmail.com
Sun Nov 29 18:42:57 UTC 2009
* 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.
More information about the ubuntu-users
mailing list