rmyorston / busybox-w32

WIN32 native port of BusyBox.
https://frippery.org/busybox
Other
693 stars 126 forks source link

Search position of substring inside a string #463

Closed ale5000-git closed 3 weeks ago

ale5000-git commented 3 weeks ago

With Bash I can get the position by using : echo '012my_substring345' | grep -F -o -b -- 'my_substring'

Is there a way to get it on busybox? (possibly sticking to POSIX code)

avih commented 3 weeks ago
# $1: haystack  $2: needle
printpos() {
    [ -z "${2-}" ] && echo 0 ||
    { set -- "$1" "${1%%"$2"*}" && [ "$1" != "$2" ] && echo ${#2}; }
}

This prints 0-based pos of $2 in $1, or error if $2 is not a substring of $1.

ale5000-git commented 3 weeks ago

Works perfectly, thanks.