On 13Jun2007 18:18, Michael Sullivan <[EMAIL PROTECTED]> wrote:
| Is there a Linux utility that will return the position of the first
| occurrence of a specific character? Ex:
| 
| echo "example" | char-utility 'x' would return 2?

A tiny python or awk or perl script?

There isn't a utility specially made for that particular operation that
I know of. On some systems this:

  echo example | { IFS=x; read a b; expr length "$a"; }

Gets you "1". It is not portable (expr does not have a "length" operator
on all systems). However, it is a bit of a step to get the 2, because
you can't just add 1 - you do not know if there was an "x". (Going
"echo a | ..." also gets "1". This:

  sep=x # in your hypothetical script you would say "sep=$1"
  echo example \
  | { read -r line
      case $line in
        *$sep*)
          # pick a marker that is not the separator
          if [ "x$sep" = x_ ]
          then  mark=:
          else  mark=_
          fi
          # rewrite $1 etc using $line, split up by $sep
          IFS=$sep set -- $mark$line
          expr length "$1"
          ;;
        *)
          echo 0
          ;;
      esac
    }

Should do the trick without resorting to awk/python/perl at all.
You would put the whole { ... } bit into a shell script, setting
$sep from $1.

The $mark serves two purposes: firstly it ensures that there is at least
one character in $1 (otherwise strings starting with the separator would
not come out right) and it also increases the length of $1 by one
character, which neatly gets you the position of the separator.
-- 
Cameron Simpson <[EMAIL PROTECTED]> DoD#743
http://www.cskk.ezoshosting.com/cs/


To unsubscribe from this list, please email [EMAIL PROTECTED] & you will be 
removed. 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/LINUX_Newbies/

<*> Your email settings:
    Individual Email | Traditional

<*> To change settings online go to:
    http://groups.yahoo.com/group/LINUX_Newbies/join
    (Yahoo! ID required)

<*> To change settings via email:
    mailto:[EMAIL PROTECTED] 
    mailto:[EMAIL PROTECTED]

<*> To unsubscribe from this group, send an email to:
    [EMAIL PROTECTED]

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/
 

Reply via email to