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