计算 bash 中没有空格的符号
Counting symbols without spaces in bash
我想创建脚本来计算字符串 "word blah-blah word one more time word again" 中的符号。它只会计算 "word" 之前的符号,并且每个 "word" 都应该写入新字符串。所以脚本的输出应该是这样的:
word 0 ## (no symbols)
word 9 ##blah-blah
word 11 ##one more time
这一刻我得到的一切:
#!/bin/bash
$word="word blah-blah word one more time word again"
echo "$word" | grep -o word
输出仅显示来自 $word 的 "word"。我如何计算 "word" 之前的字符?
一个bash
解决方案:
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
来自 bash
人:
${#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.
说明
for w in $word;do
:用于使用空格作为分隔符将 word 字符串拆分为 单个 word 变量:w.
[[ $w != "word" ]] && (( c+= ${#w} )) && continue
:如果w
不是word
,将当前字符串(${#w}
)中的字符数存储到c
计数器中,然后继续下一个单词(continue
) 无需进一步处理。
当文字word成立时,打印计数器的值并初始化它(c=0
)
结果
word 0
word 9
word 11
我想创建脚本来计算字符串 "word blah-blah word one more time word again" 中的符号。它只会计算 "word" 之前的符号,并且每个 "word" 都应该写入新字符串。所以脚本的输出应该是这样的:
word 0 ## (no symbols)
word 9 ##blah-blah
word 11 ##one more time
这一刻我得到的一切:
#!/bin/bash
$word="word blah-blah word one more time word again"
echo "$word" | grep -o word
输出仅显示来自 $word 的 "word"。我如何计算 "word" 之前的字符?
一个bash
解决方案:
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
来自 bash
人:
${#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.
说明
for w in $word;do
:用于使用空格作为分隔符将 word 字符串拆分为 单个 word 变量:w.
[[ $w != "word" ]] && (( c+= ${#w} )) && continue
:如果w
不是word
,将当前字符串(${#w}
)中的字符数存储到c
计数器中,然后继续下一个单词(continue
) 无需进一步处理。
当文字word成立时,打印计数器的值并初始化它(c=0
)
结果
word 0
word 9
word 11