计算文件

时间:2018-04-07 21:42:20

标签: bash count ascii

我正在编写一个bash脚本,它将计算[],(),{},'',“”,“`和//的出现次数,以便我可以调试其他脚本以便丢失其中一个脚本。 这是代码:

a=0; b=0; cc=0; d=0; e=0; f=0; g=0; h=0; i=0; j=0   # set default values
squote=`echo -e "\x27"`
dquote=`echo -e "\x22"`

while IFS= read -r -n1 c; do
  [ "$c" == "[" ] && (( a++ ))
  [ "$c" == "]" ] && (( b++ ))
  [ "$c" == "(" ] && (( cc++ ))     # i imported this line from another online script, is there a reason why the author avoids (( c++ )) ?
  [ "$c" == ")" ] && (( d++ ))
  [ "$c" == "{" ] && (( e++ ))
  [ "$c" == "}" ] && (( f++ ))
  [ "$c" == "\x27" ] && (( g++ ))    # single quote
  [ "$c" == "$dquote" ] && (( h++ ))  # double quote
  [ "$c" == '`' ] && (( i++ ))        # back tick
  [ "$c" == '/' ] && (( j++ ))        # forward slash
done < "$1"

echo '[]'="$a,$b"
echo '()'="$cc,$d"
echo '{}'="$e,$f"
echo "$squote" ="$g"
echo "$dquote" ="$h"
echo '``'="$i"
echo '/'="$j"      # when used this way: /hello/ 

问题: 1)为什么cc ++而不是c ++ 2)为什么有些结果根本不正确。 3)如何以正确的方式注释特殊字符。 提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

一些简化和功能脚本

#!/bin/bash

a=0; b=0; c=0; d=0; e=0; f=0; g=0; h=0; i=0; j=0

while read -r -n1 char; do
    case "$char" in
        "[" ) (( a++ )) ;;
        "]" ) (( b++ )) ;;
        "(" ) (( c++ )) ;;
        ")" ) (( d++ )) ;;
        "{" ) (( e++ )) ;;
        "}" ) (( f++ )) ;;
        "'" ) (( g++ )) ;;
        '"' ) (( h++ )) ;;
        '`' ) (( i++ )) ;;
        '/' ) (( j++ )) ;;
    esac
done <<< "[]{}()/"$'\x60'$'\x22'$'\x27'     # $'\x60' == backtick

echo '[]'="$a,$b"
echo '()'="$c,$d"
echo '{}'="$e,$f"
echo "'" ="$g"
echo '"' ="$h"
echo '`'="$i"
echo '/'="$j"

输出

[]=1,1
()=1,1
{}=1,1
' =1
" =1
`=1
/=1

NOTA:

 prefer:  dquote=$( echo -e "\x22" )   # and not ``
 better:  dquote=$'\x22'    # or \042 octal
 simpler: dquote='"'

检查脚本并了解,我建议安装 shellcheck 或使用https://www.shellcheck.net/

最初:

    [ "$char" == "[" ] && (( a++ ))
    [ "$char" == "]" ] && (( b++ ))
    [ "$char" == "(" ] && (( c++ ))
    [ "$char" == ")" ] && (( d++ ))
    [ "$char" == "{" ] && (( e++ ))
    [ "$char" == "}" ] && (( f++ ))
    [ "$char" == "'" ] && (( g++ ))
    [ "$char" == '"' ] && (( h++ ))
    [ "$char" == '`' ] && (( i++ ))
    [ "$char" == '/' ] && (( j++ ))

但系统地执行了不必要的测试。 我们也可以使用:

    if [[ $char == "[" ]]; then (( a++ ))
    elif [[ $char == "]" ]]; then (( b++ ))
    ...

但是有10,000次迭代的表演:

   if   > if elif > case  
6720 ms > 2895 ms > 2073 ms