5

is there a way to get indexOf of a substring after nth character in Bash, without needing to cut the original string one by one, that would be lengthy

              12345678901234
$ expr index 'abcdeabcdabcaa' 'c'
3
$ expr index 'abcdeabcdabcaa' 'ca'
1 

What i want would be:

$ indexOf 'abcdeabcdabcaa' 'ca'
12
$ indexOfAfter 5 'abcdeabcdabcaa' 'c'
8
$ indexOfAfter 5 'abcdeabcdabcaa' 'ca'
12
$ indexOfAfter 9 'abcdeabcdabcaa' 'b'
11
$ indexOfAfter 111 'abcdeabcdabcaa' 'c'
0

probably there are already function on Bash to do this.. this is not a homework, just out of curiosity..

Kokizzu
  • 24,974
  • 37
  • 137
  • 233
  • possible duplicate of [Bash: Find position of character in a string under OS X](http://stackoverflow.com/questions/17615750/bash-find-position-of-character-in-a-string-under-os-x) – chepner Jul 17 '13 at 12:00

1 Answers1

6

both operations implemented with awk

contents of file indexOf:

echo "$1" "$2" | awk '{print index($1,$2)}' 

e.g.

 indexOf 'abcdeabcdabcaa' 'ca'
 12

contents of file indexOfAfter:

echo "$1" "$2" "$3" | \
awk '{s=substr($2,$1);posn=index(s,$3);if (posn>0) print $1+posn-1; else print 0;}'
suspectus
  • 16,548
  • 8
  • 49
  • 57