2

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"?

Nick
  • 55
  • 1
  • 10
  • You mean count characters? Do this with `awk`. Set the record separator to `word`, then print `length($0)`. – Barmar Mar 26 '18 at 06:54

1 Answers1

2

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
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52
  • Thank you. Can you explain how this code (( c+= ${#w} )) counts symbols without spaces? – Nick Mar 26 '18 at 07:13