
我們在先前的文章中多次提到過 head 命令,它是在 Linux 終端中查看文本文件的一種方式,我們可以使用 head 命令從文件的開始部分打印指定行數(shù)的內(nèi)容。
它的語法結(jié)構(gòu)如下所示:
今天我們通過例子就 head 命令介紹一些實(shí)際工作中可能會(huì)用到的知識(shí)。
關(guān)于 head 命令的一些例子
作為演示,我們使用如下內(nèi)容的文本文件:?
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
首先,在不使用任何選項(xiàng)的情況下,使用 head 命令查看文本文件,默認(rèn)會(huì)顯示文件的前 10 行內(nèi)容,如下所示:?
$ 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
當(dāng)然如果文件內(nèi)容不足 10 行,那么就會(huì)顯示整個(gè)文件的內(nèi)容。
使用 head 命令打印文件前 n 行
使用 head 命令,打印文件的前 n 行,需要使用選項(xiàng) -n,后面跟一個(gè)行數(shù)。比如,要打印文件多大前 3 行,可使用如下命令:?
$ head -n 3 tiap.txt
The Mysterious Affair at Styles
The Secret Adversary
The Murder on the Links
打印除了最后 n 行以外所有的內(nèi)容
上面例子中,行數(shù)如果為負(fù)值,比如 -3,那么就會(huì)打印除了最后 3 行以外所有的內(nèi)容,如下所示:?
$ 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 命令打印多個(gè)文件
使用 head 命令可以同時(shí)查看多個(gè)文件,語法如下:
head -n N file1 file2 file3
比如,有兩個(gè)文件,想要同時(shí)查看這兩個(gè)文件的前兩行,如下命令:?
$ 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
如上面例子中的輸出所示,每個(gè)文件的輸出都會(huì)使用 =>filename<== 分隔。
處理輸出中的頭信息
上面的例子,其輸出中帶有文件名來分割不同文件的內(nèi)容,如果不想看到這個(gè)分割信息(文件頭信息),可以使用 -q 選項(xiàng)(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
另外一個(gè)問題,你可能也注意到了,就是在打印單個(gè)文件的時(shí)候,其輸出中是不帶文件頭信息的,可以使用 -v 選項(xiàng)強(qiáng)制讓其打印文件名,如下所示:?
$ head -v -n 2 tiap.txt
==> tiap.txt <==
The Mysterious Affair at Styles
The Secret Adversary
打印指定大小的字節(jié)/字符數(shù)
使用 head 命令還可以打印指定字節(jié)數(shù)的內(nèi)容,使用 -c 選項(xiàng)來實(shí)現(xiàn),后面跟字節(jié)數(shù)。
一般來說,一個(gè)字符的大小就是一個(gè)字節(jié),所以也可以把它當(dāng)作是打印一定數(shù)量的字符數(shù)。如下:?
與行數(shù)類似,使用 -c 選項(xiàng)后面指定一個(gè)負(fù)數(shù),可以打印除了最后指定數(shù)量的字符以外其他的所有內(nèi)容,如下所示:
使用 head 和 tail 命令組合,打印文件的指定幾行
前面我們介紹過一篇文章,??如何在 Linux 命令行中顯示某個(gè)文件中指定的幾行文字??
介紹了使用 head 命令和 tail 命令打印文件中的指定幾行內(nèi)容,大家感興趣可以去看一下。