跟我一起写Shell脚本之十八--常用命令(head)

1、介绍

    head也是我们经常在脚本中用到的一个命令,主要用来显示文件的开头部分内容。我们可以用man head查看下它的介绍:

NAME
       head - output the first part of files

SYNOPSIS
       head [OPTION]... [FILE]...

DESCRIPTION
       Print  the  first  10 lines of each FILE to standard output.  With more
       than one FILE, precede each with a header giving the file name.

       With no FILE, or when FILE is -, read standard input.

       Mandatory arguments to long options are  mandatory  for  short  options
       too.

       -c, --bytes=[-]NUM
              print  the  first  NUM bytes of each file; with the leading '-',
              print all but the last NUM bytes of each file

       -n, --lines=[-]NUM
              print the first NUM lines instead of  the  first  10;  with  the
              leading '-', print all but the last NUM lines of each file

       -q, --quiet, --silent
              never print headers giving file names

       -v, --verbose
              always print headers giving file names

       -z, --zero-terminated
              line delimiter is NUL, not newline

       --help display this help and exit

       --version
              output version information and exit

       NUM may have a multiplier suffix: b 512, kB 1000, K 1024, MB 1000*1000,
       M 1024*1024, GB 1000*1000*1000, G 1024*1024*1024, and so on for  T,  P,
       E, Z, Y.

2、用法总结

    我们用一个表格来总结下其用法:

编号 功能 命令
1 显示文件前10行(默认10行) head xxx.txt
2 显示文件前3行 head -n 3 xxx.txt
3 显示文件除了最后3行的所有行 head -n -3 xxx.txt
4 显示文件前3个字节 head -c 3 xxx.txt
5 显示文件除了最后3字节的所有字节 head -c -3 xxx.txt
6 不显示文件名(默认就不显示) head -q xxx.txt
7 显示文件名 head -v xxx.txt
8 显示多个文件的前5行内容 head -n 5 xxx1.txt xxx2.txt

3、例子

    我们准备两个文件xxx1.txt和xxx2.txt,内容都为:

11
22
33
44
55
66
77
88
99
aa
bb
cc
dd
ee
ff

3.1 显示文件前10行(默认10行)

$ head xxx1.txt 
11
22
33
44
55
66
77
88
99
aa

3.2 显示文件前3行

$ head -n 3 xxx1.txt 
11
22
33

3.3 显示文件除了最后3行的所有行

$ head -n -3 xxx1.txt 
11
22
33
44
55
66
77
88
99
aa
bb
cc

3.4 显示文件前3个字节

$ head -c 3 xxx1.txt 
11

这里应该包含换行符。

3.5 显示文件除了最后3字节的所有字节

$ head -c -3 xxx1.txt 
11
22
33
44
55
66
77
88
99
aa
bb
cc
dd
ee

3.7显示文件名

$ head -v -n 3 xxx1.txt 
==> xxx1.txt <==
11
22
33

3.8 显示多个文件的前5行内容

$ head -n 3 xxx1.txt xxx2.txt 
==> xxx1.txt <==
11
22
33

==> xxx2.txt <==
11
22
33

我们应该发现了,默认会输出文件名的。如果我们加上-q会怎样呢?

$ head -q -n 3 xxx1.txt xxx2.txt 
11
22
33
11
22
33

好了,今天的部分就到这里了,接下来的Shell脚本之旅会更久精彩!

===================================================================================

注意:本文为本人原创,版权所属为个人所有,欢迎转载,但是转载请注明出处。

===================================================================================

Guess you like

Origin blog.csdn.net/sjwangjinbao/article/details/118227297