
我們在先前的文章中多次提到過 head 命令,它是在 Linux 終端中查看文本文件的一種方式,我們可以使用 head 命令從文件的開始部分打印指定行數的內容。
它的語法結構如下所示:
今天我們通過例子就 head 命令介紹一些實際工作中可能會用到的知識。
關于 head 命令的一些例子
作為演示,我們使用如下內容的文本文件:?
The Mysterious Affair at Styles
The Secret Adversary
The Murder on the Links
The Man in the Brown Suit
The Secret of Chimneys
The Murder of Roger Ackroyd
The Big Four
The Mystery of the Blue Train
The Seven Dials Mystery
The Murder at the Vicarage
Giant's Bread
The Floating Admiral
The Sittaford Mystery
Peril at End House
Lord Edgware Dies
Murder on the Orient Express
Unfinished Portrait
Why Didn't They Ask Evans?
Three Act Tragedy
Death in the Clouds
首先,在不使用任何選項的情況下,使用 head 命令查看文本文件,默認會顯示文件的前 10 行內容,如下所示:?
$ head tiap.txt
The Mysterious Affair at Styles
The Secret Adversary
The Murder on the Links
The Man in the Brown Suit
The Secret of Chimneys
The Murder of Roger Ackroyd
The Big Four
The Mystery of the Blue Train
The Seven Dials Mystery
The Murder at the Vicarage
當然如果文件內容不足 10 行,那么就會顯示整個文件的內容。
使用 head 命令打印文件前 n 行
使用 head 命令,打印文件的前 n 行,需要使用選項 -n,后面跟一個行數。比如,要打印文件多大前 3 行,可使用如下命令:?
$ head -n 3 tiap.txt
The Mysterious Affair at Styles
The Secret Adversary
The Murder on the Links
打印除了最后 n 行以外所有的內容
上面例子中,行數如果為負值,比如 -3,那么就會打印除了最后 3 行以外所有的內容,如下所示:?
$ head -n -3 agatha.txt
The Mysterious Affair at Styles
The Secret Adversary
The Murder on the Links
The Man in the Brown Suit
The Secret of Chimneys
The Murder of Roger Ackroyd
The Big Four
The Mystery of the Blue Train
The Seven Dials Mystery
The Murder at the Vicarage
Giant's Bread
The Floating Admiral
The Sittaford Mystery
Peril at End House
Lord Edgware Dies
Murder on the Orient Express
Unfinished Portrait
使用 head 命令打印多個文件
使用 head 命令可以同時查看多個文件,語法如下:
head -n N file1 file2 file3
比如,有兩個文件,想要同時查看這兩個文件的前兩行,如下命令:?
$ head -n 2 tiap.txt sherlock.txt
==> tiap.txt <==
The Mysterious Affair at Styles
The Secret Adversary
==> sherlock.txt <==
A Scandal in Bohemia
The Red-Headed League
如上面例子中的輸出所示,每個文件的輸出都會使用 =>filename<== 分隔。
處理輸出中的頭信息
上面的例子,其輸出中帶有文件名來分割不同文件的內容,如果不想看到這個分割信息(文件頭信息),可以使用 -q 選項(quiet 模式)將頭信息省略掉:?
$ head -q -n 2 tiap.txt sherlock.txt
The Mysterious Affair at Styles
The Secret Adversary
A Scandal in Bohemia
The Red-Headed League
另外一個問題,你可能也注意到了,就是在打印單個文件的時候,其輸出中是不帶文件頭信息的,可以使用 -v 選項強制讓其打印文件名,如下所示:?
$ head -v -n 2 tiap.txt
==> tiap.txt <==
The Mysterious Affair at Styles
The Secret Adversary
打印指定大小的字節/字符數
使用 head 命令還可以打印指定字節數的內容,使用 -c 選項來實現,后面跟字節數。
一般來說,一個字符的大小就是一個字節,所以也可以把它當作是打印一定數量的字符數。如下:?
與行數類似,使用 -c 選項后面指定一個負數,可以打印除了最后指定數量的字符以外其他的所有內容,如下所示:
使用 head 和 tail 命令組合,打印文件的指定幾行
前面我們介紹過一篇文章,??如何在 Linux 命令行中顯示某個文件中指定的幾行文字??
介紹了使用 head 命令和 tail 命令打印文件中的指定幾行內容,大家感興趣可以去看一下。