Count occurrences of character per line/field on Unix

后端 未结 10 2119
难免孤独
难免孤独 2020-12-23 16:19

Given a file with data like this (ie stores.dat file)

sid|storeNo|latitude|longitude
2tt|1|-28.0372000t0|153.42921670
9|2t|-33tt.85t09t0000|15t1.03274200
         


        
10条回答
  •  情歌与酒
    2020-12-23 16:49

    No need for awk or perl, only with bash and standard Unix utilities:

    cat file | tr -c -d "t\n" | cat -n |
      { echo "count   lineNum"
        while read num data; do
          test ${#data} -gt 0 && printf "%4d   %5d\n" ${#data} $num
        done; }
    

    And for a particular column:

    cut -d "|" -f 2 file | tr -c -d "t\n" | cat -n |
      { echo -e "count lineNum"
        while read num data; do
          test ${#data} -gt 0 && printf "%4d   %5d\n" ${#data} $num
        done; }
    

    And we can even avoid tr and the cats:

    echo "count   lineNum"
    num=1
    while read data; do
      new_data=${data//t/}
      count=$((${#data}-${#new_data}))
      test $count -gt 0 && printf "%4d   %5d\n" $count $num
      num=$(($num+1))
    done < file
    

    and event the cut:

    echo "count   lineNum"
    num=1; OLF_IFS=$IFS; IFS="|"
    while read -a array_data; do
      data=${array_data[1]}
      new_data=${data//t/}
      count=$((${#data}-${#new_data}))
      test $count -gt 0 && printf "%4d   %5d\n" $count $num
      num=$(($num+1))
    done < file
    IFS=$OLF_IFS
    

提交回复
热议问题