用head查看文本文件的开头
2017-08-26
该head命令是用于查看文本文件开头的核心Linux实用程序。尽管其功能较窄,但head在许多系统管理和脚本编写任务中都非常有用。对于解决文件结尾的类似功能,请考虑尾部实用程序。
使用head命令
考虑以下调用:
$ head /etc/rc.conf
这将打印文件的前10行/etc/rc.conf到终端上的标准输出。因此,head对于许多不同的情况是有用的,例如如果文件名不明确,则确定文件的内容。
如果文件少于10行,head将打印整个文件。
控制head命令输出长度
使用该-n选项,head可以修改输出的行数。例如:
head -n 24 /etc/logrotate.conf
这将**/etc/logrotate.conf**文件的前24行打印到终端。您可以在声明文件之前或之后指定行数。因此,以下命令与上一个命令相同:
head /etc/logrotate.conf -n 24
如果文件小于指定行数,head将打印整个文件。
用head查看多个文件的开头
head可以一次处理多个文件。考虑以下几点:
$ ls
example roster
$ head *
==> example <==
lollipop
The Joke
Jockey to the Fair
Simon's Fancy
Truckles
==> roster <==
John
Susan
Michael
Robert
Justin
Herbert
Marissa
George
Jacob
结合头与其他命令
head可用于过滤命令和文件的输出。例如:
% cat --help | head -n 2
Usage: cat [OPTION]... [FILE]...
Concatenate FILE(s), or standard input, to standard output.
$ ls /usr/lib | head
alsa-lib
ao
apr.exp
apr-util-1
aprutil.exp
aspell
aspell-0.60
avahi
awk
bmp
在第一个示例中,head过滤完整输出cat --help以仅生成命令输出的前两行。在第二个例子中,head打印ls命令输出的前十行。