Counting the number of dots in a string

前端 未结 6 1063
佛祖请我去吃肉
佛祖请我去吃肉 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:02

    Solution in pure 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}
    
    0 讨论(0)
  • 2021-01-11 11:06

    You can do it combining grep and wc commands:

    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 grep for that purpose:

    echo "string.with.dots." | grep -o "\." | grep -c "\."
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-11 11:20
    VAR="s454-da4_sd.fs_84-df.f-sds.a_as_d.a-565sd.dasd"
    echo $VAR | tr -d -c '.' | wc -c
    

    tr -d deletes given characters from the input. -c takes the inverse of given characters. together, this expression deletes non '.' characters and counts the resulting length using wc.

    0 讨论(0)
  • 2021-01-11 11:25

    awk alternative:

    echo "$VAR" | awk -F. '{ print NF - 1 }'
    

    Output:

    5
    
    0 讨论(0)
  • 2021-01-11 11:26

    Temporarily setting IFS, pure Bash, no sub-processes:

    IFS=. VARTMP=(X${VAR}X) # avoid stripping dots
    echo $(( ${#VARTMP[@]} - 1 ))
    

    Output:

    5
    
    0 讨论(0)
提交回复
热议问题