Counting the number of dots in a string

前端 未结 6 1118
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-11 10:52

How do I count the number of dots in a string in BASH? For example

VAR=\"s454-da4_sd.fs_84-df.f-sds.a_as_d.a-565sd.dasd\"

# Variable VAR contains 5 dots
         


        
6条回答
  •  长情又很酷
    2021-01-11 11:16

    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.

提交回复
热议问题