Linux中的head命令

时间:2020-03-05 15:26:59  来源:igfitidea点击:

CAT命令用于将文件的内容打印到终端上。

head是另一种在Linux中查看文本文件的方法。

我们可以使用Head命令从文件开头打印指定数量的行。

这是head命令的语法:

head [option] [filename]

head命令示例

让我们了解如何使用Linux中的Head命令使用实际的示例。

我将在此示例中使用文件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
Why Didn't They Ask Evans?
Three Act Tragedy
Death in the Clouds

如果我们没有使用Head命令使用任何选项,则默认情况下会打印前10行

head 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

如果该文件有少于十行,则当然,它将打印所有行。

1.用头命令打印顶部n行

当我们需要打印特定的行数时,可以使用-n选项后跟行数。

例如,要显示前3行,我们可以使用它:

head -n 3 agatha.txt 
 The Mysterious Affair at Styles
 The Secret Adversary
 The Murder on the Links

2.打印所有除了最后n行

我们可以在文件末尾排除特定数量的行,并通过向-n选项提供负数来打印文件的剩余内容。

例如,如果要保留文件的最后15行,则可以使用此命令:

head -n -15 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

3.使用head命令查看多个文件

我们可以将多个文件提供为ENDEN命令。

head -n N file1 file2 file3

例如,如果我们必须显示两个文件的前两行,我们可以使用这样的内容:

head -n 2 agatha.txt sherlock.txt 
 ==> agatha.txt <==
 The Mysterious Affair at Styles
 The Secret Adversary
 ==> sherlock.txt <==
 A Scandal in Bohemia
 The Red-Headed League

如我们所见,每个文件的输出都有==> filename <==。

4.处理输出中的标题

如上所述,在最后一个示例中,Head命令将文件名打印为每个文件输出以上的标题以将它们分开。

我们可以使用-q选项(安静模式)来省略输出中的文件名。

head -q -n 2 agatha.txt sherlock.txt 
 The Mysterious Affair at Styles
 The Secret Adversary
 A Scandal in Bohemia
 The Red-Headed League

我们可能还注意到标题未打印单个输入文件。
我们可以强制使用-v选项打印文件名(详细模式)。

head -v -n 2 agatha.txt 
 ==> agatha.txt <==
 The Mysterious Affair at Styles
 The Secret Adversary

注意 - 每个字符的大小是一个字节。

5.打印特定数字节/字符

如果需要打印文件的特定字节数,则可以使用-c选项后跟数字。

通常,一个字符的大小是一个字节。
所以你可以将其视为打印某些字符。

head -c3 agatha.txt 
The

我们还可以在结束时排除特定数量的行数,从而排除特定数字节。
为此,请指定为-c选项的负值。

head -c -50 agatha.txt

通过组合头部和尾部命令来打印文件的行数

如果我们想在文件中间打印n个行,该怎么办?

例如,如果要将线路从10到15中打印到文件中,则可以将Head命令与tail命令组合起来。

head -n 15 agatha.txt | tail -n +10

HEAD命令打印文件的前15行。
然后,tail命令取下该输出并打印从行号启动的所有行。
这为我们提供10到15的行。

如果我们只想打印第n行,我们可以通过再次组合head和tail来完成它。

head -n 15 agatha.txt | tail -n 1

因此,HEAD命令打印文件的前15行,然后tail命令打印此输出的最后一行。
因此,你得到第15行。