Using awk
is pretty quick:
$ awk '{ print index($0, $2); }' <<<'foo bar baz'
4
This gives the 1-based character index for the second word. Replace $2
with $1
for the first word, $3
for third, and so on or $NF
for the last word. Be careful when the nth-word is a substring of one of the preceding words.
Update based on Karakfa's clever approach:
If your nth-word is a substring of a preceding word, then you need to be more diligent:
$ cat t
foo bar baz
fobaro bar baz
bar bar baz
$ awk '{ print 1 == index($0, $2) ? 1 : index($0, " "$2)+1; }' < t
4
7
0
$ awk '{ print 1 == index($0, $5) ? 1 : index($0, " "$5)+1; }' <<<' the cat ate the bird'
20
Updated based on KiloOne's need for a function:
function position() {
local n=${1:?For what column do you want position?}
awk "{ print 1 == index(\$0, \$$n) ? 1 : index(\$0, \" \"\$$n)+1; }"
}
$ echo 'my cat ate your bird' | position 3
8
Now available on github as a bashworks module.