head 与 tail 分别为显示文件开头以及末尾的命令,是linux最常用的命令之一:
主要有以下选项:
-n 显示的行数
-v verbose 输出文件名的header
-q 不输出文件名的header
-f follow tail专用,可以实时监控文件末尾
以以下有11行的示例数据为例 head 默认可以查看文件的前十行:
$ cat test.txt
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
k 11
#head 查看开头,默认为十行
$ head test.txt
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
#tail 查看末尾,默认为十行
$ tail test.txt
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
k 11
head与 tail 使用 -n 选项可以 指定显示的行数
$ head -n 5 test.txt
a 1
b 2
c 3
d 4
e 5
tail -n 5 test.txt
g 7
h 8
i 9
j 10
k 11
-v verbose 输出时第一行显示文件名
head -v test.txt
==> test.txt <==
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
head , tail可以对多个文件使用
head test.txt test2.txt
==> test.txt <==
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
==> test2.txt <==
aaaaaa 123
aaaaab 234
aaabcd 345
使用-q (quiet)则不显示header
head -q test.txt test2.txt
a 1
b 2
c 3
d 4
e 5
f 6
g 7
h 8
i 9
j 10
aaaaaa 123
aaaaab 234
aaabcd 345
-f (follow) tail有一个额外的选项,可以实时监控文件的末尾(例如监视一个实时输出的log文件)
tail -f test.log
head 与tail组合 可以查看文件的任意行
$ head -n 7 test.txt |tail -n 1
g 7