0

I know the following expression:

echo "bob alice robert alice" | awk '{print index($0,"alice")}'
5

Will output the index of the first alice match, is there any way to get the index of all matches?, eg:

echo "bob alice robert alice" | awk 'unknown magic'
5:18
  • actually this is no magic but a simple substring shift loop. See my answer – ikrabbe Jul 14 '15 at 6:57
1

With POSIX tools chest:

echo "bob alice robert alice"| p=alice awk '
{
  while(1) {
    $0 = substr($0, RSTART+RLENGTH)
    match($0, ENVIRON["p"])
    if (RSTART == 0) break
    i = i ? i+RSTART+RLENGTH-1 : RSTART
    print i
  }
}' | paste -sd: -
5:18
1

This should do your job:

echo "bob alice robert alice" |\
awk '{
    s=$0
    o=0
    m="alice"
    l=length(m)
    i=index(s,m)
    while (i>0) {
        o+=i
        print o
        s=substr(s,i+l)
        o+=l-1
        i=index(s,m)
    }
}'

To format with the ':' (colon) you can pipe through

paste -s |tr '\t' ':'
1
echo "bob alice robert alice"| awk '
{for( i=1;i<=NF;i++) {
    if ( $i == "alice") {
          printf index($0,"alice") ":"
          gsub("alice","xxxxx",$i)
     }
}
print " "
}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.