最近几天一直在研究Bash编程

下面是我写的一个小小的功能脚本:可以通过该命令来将指定文件的指定行的附近的10行显示出来,如果你使用过gdb就知道有个叫做list的命令因此我把它一直到shell中来了当然你可以通过cat来查看文件但是如果文件比较大呢你是不是要翻很多页,多麻烦是吧!

下面提供代码:

$cat list

#! /bin/bash
# name: list
# usage: list 10 lines around the line as given
if [ $# -eq 0 -o $# -eq 1 ]
then
echo -n "Usage: list [number] [file]"
echo " list lines around number as given"
exit 1
fi

# copy the located arguments
line=$1
filename=$2

# count the total lines
# @para $1 file name
# @return total lines of file given as {@para $1}
total_lines()
{
while read tmp
do
lines=`expr $lines + 1`
done < $1
return $lines
}

total_lines $filename
if [ $line -gt $? ]
then
echo "line $line has overflowed the range of $filename"
exit 2
fi

# list lines around it
# @para $1 line number
# @para $2 file name
list_lines()
{
exec 3< $2 #open read pipe and close it in _LINE_ 87
num=1 #first line

#{@para $1} less than or equal to 5 or not
#echo lines before {@para $1} (included)
if [ $1 -le 5 ]
then
while [ $num -le $1 ]
do
if read str <& 3
then
echo "$num $str"
num=`expr $num + 1`
continue
fi
break
done
else
tmp=`expr $1 - 5`
while [ $num -le $tmp ]
do
read str <& 3
num=`expr $num + 1`
done
tmp=`expr $num + 5`
while [ $num -lt $tmp ]
do
if read str <& 3
then
echo "$num $str"
num=`expr $num + 1`
continue
fi
break
done
fi

#echo "trap here" # trap here

#echo the following lines
tmp=`expr $num + 5`

while [ $num -lt $tmp ]
do
if read str<& 3
then
echo "$num $str"
num=`expr $num + 1`
continue
fi
break
done
exec 3<&-
}

list_lines $line $filename

$chmod 755 li

$./list 45 list

41
42 #{@para $1} less than or equal to 5 or not
43 #echo lines before {@para $1} (included)
44 if [ $1 -le 5 ]
45 then
46 while [ $num -le $1 ]
47 do
48 if read str <& 3
49 then
50 echo "$num $str"
额,对了,上面的注释部分是用英文写的本人CET6还没过的写不出什么水平的,另外有些注释是仿照Java API注释写本人不是很熟悉,只能写出个大概意思了!

posted on 2012-04-30 11:20  Junhv.W  阅读(1797)  评论(0编辑  收藏  举报