第四章:Tweaking Unix--31.顯示帶有行號的文件

   有許多種方法能夠達到顯示行號的目的,某些程序甚至很簡短。好比能夠用一個awk來實現:
awk '{print NR": "$0}' < inputfile

   一樣,在某些Unix版本上,cat命令有-n選項,或是more(less, pg)也有能顯示行號的選項。但還有一些Unix的版本上,可能這些都通通沒有,那麼此時,下面的這個簡易腳本就能夠發威了: shell

#!/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-
上面的這行命令何時會頗有用呢?一個常常遇到的狀況就是,你想顯示一個日誌文件的時候,
相關文章
相關標籤/搜索