每行的文件unix中的字节数

时间:2015-01-06 14:11:14

标签: shell unix 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"

1 个答案:

答案 0 :(得分:5)

您的方法非常好,只需要执行a=$(wc -c <<< "$line")a=$(echo "$line" | wc -w),无需管道awk。另外,请注意493条件中的if后需要额外的空格。

所有在一起:

#!/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"
相关问题