不过Unix提供了足够多的工具让咱们使用,只要咱们可以好好的发现,并经过管道将它们优美的链接起来。好比,要快速的扫描一个文件,看看哪些行过长: git
awk '{if (length($0) > 72) {print $0}}' filename还有一个有趣点的方法,就是使用shell中的$#vamname结构,它会返回任意一个替换了vamname的变量的长度(指内容,不是变量名)。
#!/bin/sh # toolong.sh -- 使用fmt.sh格式化那些超过指定长度的长行 width=72 if [ ! -r "$1" ]; then echo "Usage: `basename $0` filename" >&2 exit 1 fi while read input do if [ ${#input} -gt $width ]; then echo "$input" | fmt.sh else echo "$input" fi done < $1 exit 0这个脚本中处理输入文件的方法颇有意思。首先用一个简单的 <$1 达到输入文件的目的,而后用一个 read input 将每行都解析下。
varlength="$(echo "$var" | wc -c)"可是,wc命令有一个十分让人生厌的特性,它的输出会有一个前导空格,目的是让输出列表排列的漂亮些。为了回避这个讨厌的问题,会有一个微小的改动,就是在经过最后一个管道时,只容许数字经过:[注: 在个人Linux中,没发现做者说的这个特性,而且使用了sed后,可能会有问题,需读者在本身的环境中检验]
varlength="$(echo "$var" | wc -c | sed 's/[^:digit:]//')"运行结果:
$ toolong ragged.txt So she sat on, with closed eyes, and half believed herself in Wonderland, though she knew she had but to open them again, and all would change to dull reality--the grass would be only rustling in the wind, and the pool rippling to the waving of the reeds--the rattling teacups would change to tinkling sheep-bells, and the Queen's shrill cries to the voice of the shepherd boy--and the sneeze of the baby, the shriek of the Gryphon, and all the other queer noises, would change (she knew) to the confused clamour of the busy farm-yard--while the lowing of the cattle in the distance would take the place of the Mock Turtle's heavy sobs. Notice that, unlike a standard invocation of fmt, toolong has retained line breaks where possible, so the word "sneeze," which is on a line by itself in the input file, is also on a line by itself in the output.