每行的文件unix中的字节数

May*_*ain 4 unix shell ksh

我想计算一个文件中的所有行,其中字节数大于一个值(比如10).我怎么能这样做?

我尝试使用cat file | awk'length($0)>10'但是这给了我所有字符大于10的字符数.我想计算字节数.

我写了下面的代码,但它不起作用.它返回一些乱码输出:

#!/bin/ksh
file="a.txt"
while read line
do
    a=`wc -c "${line}"|awk {'print $1'}`
    if [ $a -ne 493]; then
    echo "${line}"
    fi
done <"$file"
Run Code Online (Sandbox Code Playgroud)

fed*_*qui 5

你的方法非常好,只有你必须做,a=$(wc -c <<< "$line")或者a=$(echo "$line" | wc -w)不需要管道awk.此外,注意493if条件之后需要额外的空间.

全部一起:

#!/bin/ksh
file="a.txt"
while read line
do
    a=$( echo -n "$line" | wc -c) # echo -n to prevent counting new line
    if [ "$a" -ne 493 ]; then
      echo "${line}"
    fi
done <"$file"
Run Code Online (Sandbox Code Playgroud)

  • @MarkSetchell是真的,只是OP想要字节长度,而不是字符,我猜`$ {#var}`返回字符.如果我们说`r ="hàllo"`(那里有一个重音),那么`echo $ {#r}`返回5,而`echo'hàllo"| wc -c`返回7. //如果我们说`r ="hallo"`(没有重音符号),`echo $ {#r}`返回5,而`echo'hallo"| wc -c`返回6. (2认同)