第四章:Tweaking Unix--33.只变换很长的行

   第14个脚本fmt.sh(这个程序没有从博客园移植过来)的一个缺陷就是,它会变换全部它碰见的一切。这可能会把本来的输入格式搞的一团糟。若是你只是想变换一下某个文档中很长的那些行,而不肯意去动别的文字的话,你要怎么办?在Unix命令行中,若是使用默认的命令集,惟一的解决办法就是:用一个编辑器,一行一行的精确搞定。把须要变换的行一行一行的格式好(好比在vim中,移动光标到须要变更的行上,而后 !$fmt)。

不过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 将每行都解析下。
   若是你的shell环境中没有 ${#var} 记法的话,可使用以下方法代替:
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.
相关文章
相关标签/搜索