Linux中head命令的5个实例

您可能知道 cat 命令用于将文件的内容打印到终端上。 这 命令将整个文件打印到终端上。

Head 是在 Linux 中查看文本文件的另一种方式。 您可以使用 命令从文件的开头打印指定数量的行。

以下是 head 命令的语法:

head [option] [filename]

head命令的7个例子

让我们通过实例来学习如何在 Linux 中使用 head 命令。

我将使用该文件 阿加莎.txt 在这 example 这是这个文本文件的内容。 您可以下载该文件以在遵循本教程的同时练习命令:

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.用head命令打印前N行

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

为了 example,要显示前 3 行,您可以使用以下命令:

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

2. 打印除最后 N 行以外的所有内容

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

为了 example,如果要保留文件的最后 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命令使用多个文件

您可以提供多个文件作为 head 命令的输入。

head -n N file1 file2 file3

为了 example,如果你必须显示两个文件的前两行,你可以使用这样的东西:

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

如您所见,每个文件的输出用 ==> 文件名 <== 分隔。

4. 处理输出中的header

正如你在上次看到的 examplehead 命令将文件名打印为每个文件输出上方的标题以分隔它们。

您可以使用 -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

额外提示:通过组合 head 和 tail 命令打印文件的 N 行

如果你想在文件中间打印 N 行怎么办?

为了 example,如果要打印文件的第 10 到 15 行,可以将 head 命令与 tail 命令结合使用。

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

head 命令打印文件的前 15 行。 然后 tail 命令获取此输出并打印从第 10 行开始的所有行。这将为您提供从 10 到 15 的行。

如果你只想打印第 n 行,你可以通过重新组合 head 和 tail 来完成。

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

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

我希望您已经了解 head 命令及其选项的用法。 如果您有任何疑问,请在下方评论!