rmyorston / busybox-w32

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

Search position of substring inside a string #463

Closed ale5000-git closed 1 month ago

ale5000-git commented 1 month 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 1 month 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 1 month ago

Works perfectly, thanks.