bash 计算字符串中的点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11953185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting the number of dots in a string
提问by Charlie
How do I count the number of dots in a string in BASH? For example
如何在 BASH 中计算字符串中的点数?例如
VAR="s454-da4_sd.fs_84-df.f-sds.a_as_d.a-565sd.dasd"
# Variable VAR contains 5 dots
回答by Rostyslav Dzinko
You can do it combining grepand wccommands:
你可以结合grep和wc命令来做到这一点:
echo "string.with.dots." | grep -o "\." | wc -l
Explanation:
解释:
grep -o # will return only matching symbols line/by/line
wc -l # will count number of lines produced by grep
Or you can use only grepfor that purpose:
或者您只能grep为此目的使用:
echo "string.with.dots." | grep -o "\." | grep -c "\."
回答by perreal
VAR="s454-da4_sd.fs_84-df.f-sds.a_as_d.a-565sd.dasd"
echo $VAR | tr -d -c '.' | wc -c
tr -ddeletes given characters from the input. -ctakes the inverse of given characters. together, this expression deletes non '.' characters and counts the resulting length using wc.
tr-d从输入中删除给定的字符。-c取给定字符的倒数。一起,此表达式删除非 '.' 字符并使用wc.
回答by rush
Solution in pure bash:
纯解决方案bash:
VAR="s454-da4_sd.fs_84-df.f-sds.a_as_d.a-565sd.dasd"
VAR_TMP="${VAR//\.}" ; echo $((${#VAR} - ${#VAR_TMP}))
or even just as chepner mentioned:
甚至就像切普纳提到的那样:
VAR="s454-da4_sd.fs_84-df.f-sds.a_as_d.a-565sd.dasd"
VAR_TMP="${VAR//[^.]}" ; echo ${#VAR_TMP}
回答by Thor
awkalternative:
awk选择:
echo "$VAR" | awk -F. '{ print NF - 1 }'
Output:
输出:
5
回答by nneonneo
Temporarily setting IFS, pure Bash, no sub-processes:
临时设置IFS,纯Bash,无子进程:
IFS=. VARTMP=(X${VAR}X) # avoid stripping dots
echo $(( ${#VARTMP[@]} - 1 ))
Output:
输出:
5
回答by chepner
VAR="s454-da4_sd.fs_84-df.f-sds.a_as_d.a-565sd.dasd"
dot_count=$( IFS=.; set $VAR; echo $(( $# - 1 )) )
This works by setting the field separator to "." in a subshell and setting the positional parameters by word-splitting the string. With N dots, there will be N+1 positional parameters. We finish by subtracting one from the number of positional parameters in the subshell and echoing that to be captured in dot_count.
这通过将字段分隔符设置为“.”来实现。在子shell中并通过对字符串进行分词来设置位置参数。对于 N 个点,将有 N+1 个位置参数。我们通过从 subshell 中的位置参数数量中减去 1 并回显要在dot_count.

