檢查文件兩個互補的命令是head
和tail
, 它們分別用於查看文件的開始(頭部)和結束(尾部).head
命令展現了文件的前10行。(Listing 11).html
##Listing 11: 查看示例文件的開始
$ head sonnets.txt
Shake-speare's SonnetswebI服務器
From fairest creatures we desire increase,
That thereby beauty's Rose might never die,
But as the riper should by time decease,
His tender heir might bear his memory:
But thou contracted to thine own bright eyes,
Feed'st thy light's flame with self-substantial fuel學習
一樣的,tail
展現了文件的結尾後10行(Listing 12)測試
Listing 12:查看示例文件的末尾
$ tail sonnets.txt
The fairest votary took up that fire
Which many legions of true hearts had warm'd;
And so the general of hot desire
Was, sleeping, by a virgin hand disarm'd.
This brand she quenched in a cool well by,
Which from Love's fire took heat perpetual,
Growing a bath and healthful remedy,
For men diseas'd; but I, my mistress' thrall,
Came there for cure and this by that I prove,
Love's fire heats water, water cools not love.this
當你肯定只須要檢查文件的開始和結尾時(也是經常使用場景),這兩個命令就很是有用了。rest
順便說一下,我已經忘記head
和tail
默認顯示了多少行。因爲這裏默認只顯示了10行,我還能夠手動去數,但事實上,可使用wc
命令(「wordcount」簡寫,圖16)來計算。日誌
對wc
使用較多的場景是在整個文件上,例如,咱們能夠經過wc
運行sonnets.txt
文件:code
$ wc sonnets.txt 2620 17670 95635 sonnets.txt
3個數字分別表示該文件的行數,單詞數,字節數。因此這個文件有2620行(正如3.1章節末尾獲得的答案),17670個單詞,95635個字節。htm
如今你可能猜到了數head sonnets.txt
的行數的方法。像這樣特別地,咱們能夠結合head
和重定向操做符(2.1章節)建立只有該內容的文件,而後對該文件執行wc
命令,正如Listing 13:
Listing 13: 重定向
head
內容,並對其結果應用wc
命令$ head sonnets.txt > sonnets_head.txt
$ wc sonnets_head.txt
10 46 294 sonnets_head.txt
從Listing 13中能夠看到head wc
有10行(46個單詞,294字節)。一樣的方法,也能檢查tail
結果。
另外一方面,你可能也以爲只爲了wc
能夠執行而建立中間文件不友好,確實也有個方法能夠避免它,那就是使用管道技術。Listing 14展現瞭如何作:
Listing 14: 經過
wc
管道鏈接head
$ head sonnets.txt | wc
10 46 294
Listing 14的命令執行了head sonnets.txt
而後使用管道符號|
(在多數的QWERTY鍵盤中使用shift+ 反斜線)來管道鏈接wc
的結果。這能運行的緣由是wc
命令,額外接受文件名做爲參數,(和多數的Unix程序樣)能夠經過"標準輸入"(與1.2章節提到的"標準輸出"相反),在這個例子中是sonnets.txt
文件中head
的輸出像Listing 11.wc
程序接受這個輸入而且像爲文件計數樣計算它,一樣如Listing 13那樣以行數,單詞數,字節數的順序輸出。
1.經過wc
輸出管道鏈接tail sonnets.txt
的結果,確認(像head
那樣)tail
命令的輸出默認顯示10行。
2.運行man head
命令,學習如何查看文件的前n行。實踐練習給n設置不一樣的值,找到 用head
命令顯示整個文件中的第一首詩(插圖12).
3.根據前面對tail
的練習(使用合適的選項)只輸出第一首詩的14行。備註:這條命令看起來像head -n <i> sonnets.txt | tail -n <j>
, <i>
和 <j>
表明-n
選項的數字參數。
4.tail
一個最有用的應用是運行tail -f
來查看文件是否改變。這經常使用於監測文件活動記錄,例如,web服務器,一個衆所周知的項目是跟蹤日誌文件.爲模仿建立一個日誌文件,執行ping learnenough.com > learnenough.log
在一個終端標籤窗口。(ping
命令測試是否能鏈接一個服務器)在另外一個終端標籤窗口中,輸入命令跟蹤日誌文件(這時,兩個標籤窗口都會卡住,因此一旦掌握了tail -f
的要點,使用Box4逃離窘境)。