第四章:Tweaking Unix--31.显示带有行号的文件

   有许多种方法可以达到显示行号的目的,某些程序甚至很简短。比如可以用一个awk来实现:
awk '{print NR": "$0}' < inputfile

   同样,在某些Unix版本上,cat命令有-n选项,或是more(less, pg)也有能显示行号的选项。但还有一些Unix的版本上,可能这些都统统没有,那么此时,下面的这个简易脚本就可以发威了:

#!/bin/sh

# numberlines.sh -- 效果等同于cat -n命令

for filename
do
	linecount="1"
	while read line
	do
		echo "${linecount}: $line"
		linecount="$(($linecount+1))"
	done < $filename
done

exit 0
   这个脚本可以接受任意多的文件作为输入,但是不能通过管道给它提供输入。当然,若有需要可以修改下程序。
测试下脚本:
$ numberlines text.snippet.txt 
1: Perhaps one of the most valuable uses of shell scripts is to fix 
2: your particular flavor of Unix and make it more like other flavors, 
3: to bring your commands into conformance or to increase consistency 
4: across different systems. The outsider view of Unix suggests a 
5: nice, uniform command-line experience, helped along by the existence 
6: of and compliance with the POSIX standards for Unix. But anyone who's 
7: ever touched more than one computer knows how much they can vary 
8: within these broad parameters.
如果你有了一个标记出行号的文件,那么此时你就可以反转文件了:
cat -n filename | sort -nr | cut -c8-
上面的这行命令什么时候会很有用呢?一个经常遇到的情况就是,你想显示一个日志文件的时候,

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值