Linux 中的 Head 命令 [5 个基本示例]
在本文中,您将学习 Linux 中 head 命令的一些基本示例。
您可能知道 cat 命令用于将文件的内容打印到终端上。 cat 命令将整个文件打印到终端上。
Head 是 Linux 中查看文本文件的另一种方式。您可以使用 head 命令从文件开头打印指定的行数。
head 命令的语法如下:
head [option] [filename]
head命令的7个例子
下面通过实际例子来学习如何在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.用head命令打印前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命令使用多个文件
您可以提供多个文件作为 head 命令的输入。
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
额外提示:通过组合 head 和 tail 命令打印文件的 N 行
如果你想在文件中间打印 N 行怎么办?
例如,如果要打印文件的第 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 命令及其选项的用法。如果您有任何疑问,请在下面评论!