不過Unix提供了足夠多的工具讓咱們使用,只要咱們可以好好的發現,並經過管道將它們優美的鏈接起來。好比,要快速的掃描一個文件,看看哪些行過長: git
awk '{if (length($0) > 72) {print $0}}' filename還有一個有趣點的方法,就是使用shell中的$#vamname結構,它會返回任意一個替換了vamname的變量的長度(指內容,不是變量名)。
#!/bin/sh # toolong.sh -- 使用fmt.sh格式化那些超過指定長度的長行 width=72 if [ ! -r "$1" ]; then echo "Usage: `basename $0` filename" >&2 exit 1 fi while read input do if [ ${#input} -gt $width ]; then echo "$input" | fmt.sh else echo "$input" fi done < $1 exit 0這個腳本中處理輸入文件的方法頗有意思。首先用一個簡單的 <$1 達到輸入文件的目的,而後用一個 read input 將每行都解析下。
varlength="$(echo "$var" | wc -c)"可是,wc命令有一個十分讓人生厭的特性,它的輸出會有一個前導空格,目的是讓輸出列表排列的漂亮些。爲了迴避這個討厭的問題,會有一個微小的改動,就是在經過最後一個管道時,只容許數字經過:[注: 在個人Linux中,沒發現做者說的這個特性,而且使用了sed後,可能會有問題,需讀者在本身的環境中檢驗]
varlength="$(echo "$var" | wc -c | sed 's/[^:digit:]//')"運行結果:
$ toolong ragged.txt 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. Notice that, unlike a standard invocation of fmt, toolong has retained line breaks where possible, so the word "sneeze," which is on a line by itself in the input file, is also on a line by itself in the output.