Search code examples
bashcountwc

Counting symbols without spaces in bash


I want to create script which will count symbols from string "word blah-blah word one more time word again". It will count symbols before "word" only and every "word" should be written to new string. So output of script should looks like that:

word 0 ## (no symbols)
word 9 ##blah-blah
word 11 ##one more time

All i got in this moment:

#!/bin/bash
$word="word blah-blah word one more time word again"
echo "$word" | grep -o word

Output show me only "word" from $word. How i can count chars before "word"?


Solution

  • A bashsolution:

    word="word blah-blah word one more time word again"
    c=0
    for w in $word;do
      [[ $w != "word" ]] && (( c+= ${#w} )) && continue
      echo $w $c
      c=0
    done
    

    From bash man:

    ${#parameter}

    Parameter length. The length in characters of the value of parameter is substituted. If parameter is * or @, the value substituted is the number of positional parameters. If parameter is an array name subscripted by *or @, the value substituted is the number of elements in the array.

    Explanation

    for w in $word;do : Used to split the word string using blank spaces as separators into single word variables: w.

    [[ $w != "word" ]] && (( c+= ${#w} )) && continue: If w is not word store the number of characters in currentstring (${#w}) into c counter and proceed to next word (continue) without further processing.

    When literal word is founded, just print the value of the counter and initialize it (c=0)

    Results

    word 0
    word 9
    word 11