第四章:Tweaking Unix--32.额外显示文件信息

   为了让用户更加便捷的了解到文件的内容,从而对用户提供帮助,该脚本的目的就是可以在显示文件本身内容的基础上,再多归纳总结几行。

#!/bin/sh

# showfile.sh -- 展示一个文件的内容, 也包括有用的额外信息

width=72

for input
do
	lines="$(wc -l < $input | sed 's/ //g')"
	chars="$(wc -c < $input | sed 's/ //g')"
	owner="$(ls -ld $input | awk '{print $3}')"
	echo "----------------------------------------------------------"
	echo "File $input($lines lines, $chars characters, owned by $owner):"
	echo "----------------------------------------------------------"
	while read line
	do
		if [ ${#line} -gt "$width" ]; then
			echo "$line" | fmt.sh | sed -e '1s/^/ /' -e '2,$s/^/+ /'
		else
			echo "$line"
		fi
	done < $input
	echo "----------------------------------------------------------"
done | more

exit 0
这个脚本的功能,大家应该看到了,多出了一些形象化的说明,统计了行数和字符数。在显示每行的内容时,最多显示72个字符,倘若多于72个,那么就截断为多行。这个脚本中最难的地方就在截断显示这儿:

echo "$line" | fmt.sh | sed -e '1s/^/ /' -e '2,$s/^/+ /'
它调用了第14个脚本fmt.sh,用来格式化输出用,最后一个管道的作用是: 
第一个sed表达式是把传过来的第一行的首字母处加上一个空格;
第二个sed表达式是把第2行到最后一行的每行的首字母处都添加上一个加号和一个空格;

测试下这个脚本:
$ showfile ragged.txt 
----------------------------------------------------------------- 
 File ragged.txt (7 lines, 639 characters, owned by taylor): 
----------------------------------------------------------------- 
   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. 
-----------------------------------------------------------------

转载于:https://my.oschina.net/u/578519/blog/108102

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值