显示带有行号的文件


显示带有行号的文件
 
  有许多种方法可以达到显示行号的目的,某些程序甚至很简短。比如可以用一个awk来实现: 
1
awk '{print NR": "$0}' < inputfile
   同样,在某些Unix版本上,cat命令有-n选项,或是more(less, pg)也有能显示行号的选项。但还有一些Unix的版本上,可能这些都统统没有,那么此时,下面的这个简易脚本就可以发威了:
 
01
#!/bin/sh
02
 
03
# numberlines.sh -- 效果等同于cat -n命令
04
 
05
for filename
06
do
07
    linecount="1"
08
    while read line
09
    do
10
        echo "${linecount}: $line"
11
        linecount="$(($linecount+1))"
12
    done < $filename
13
done
14
 
15
exit 0
   这个脚本可以接受任意多的文件作为输入,但是不能通过管道给它提供输入。当然,若有需要可以修改下程序。 
测试下脚本: 
1
$ numberlines text.snippet.txt
2
1: Perhaps one of the most valuable uses of shell scripts is to fix
3
2: your particular flavor of Unix and make it more like other flavors,
4
3: to bring your commands into conformance or to increase consistency
5
4: across different systems. The outsider view of Unix suggests a
6
5: nice, uniform command-line experience, helped along by the existence
7
6: of and compliance with the POSIX standards for Unix. But anyone who's
8
7: ever touched more than one computer knows how much they can vary
9
8: within these broad parameters.
如果你有了一个标记出行号的文件,那么此时你就可以反转文件了: 
1
cat -n filename | sort -nr | cut -c8-
上面的这行命令什么时候会很有用呢?一个经常遇到的情况就是,你想显示一个日志文件的时候.

相关内容

    暂无相关文章