Skip to content
Published on

Linux head、tailコマンドの基礎

Authors
  • Name
    Twitter

Overview

Linuxにはheadtailという便利なツールがあります。これらを活用すると、テキストファイルの先頭部分や末尾部分を確認することができます。

head document

head
NAME
     head – display first lines of a file

SYNOPSIS
     head [-n count | -c bytes] [file ...]

DESCRIPTION
     This filter displays the first count lines or bytes of each of the
     specified files, or of the standard input if no files are specified.  If
     count is omitted it defaults to 10.

     The following options are available:

     -c bytes, --bytes=bytes
             Print bytes of each of the specified files.

     -n count, --lines=count
             Print count lines of each of the specified files.

     If more than a single file is specified, each file is preceded by a header
     consisting of the string "==> XXX <==" where "XXX" is the name of the file.
tail
NAME
     tail – display the last part of a file

SYNOPSIS
     tail [-F | -f | -r] [-q] [-b number | -c number | -n number] [file ...]

DESCRIPTION
     The tail utility displays the contents of file or, by default, its standard
     input, to the standard output.

     The display begins at a byte, line or 512-byte block location in the input.
     Numbers having a leading plus ('+') sign are relative to the beginning of
     the input, for example, "-c +2" starts the display at the second byte of
     the input.  Numbers having a leading minus ('-') sign or no explicit sign
     are relative to the end of the input, for example, "-n 2" displays the last
     two lines of the input.  The default starting location is "-n 10", or the
     last 10 lines of the input.

     The options are as follows:

     -b number, --blocks=number

examples

以下のようなtest.txtファイルがあると仮定します。

test.txt
$cat test.txt
chaos and order
hello
hi
nice to meet you
and you?
thankyou
1
2
3
4
4
5
6
7
hihihihihi

head file

headの後にファイル名を入力すると、先頭から10行を出力します。

$  head test.txt
chaos and order
hello
hi
nice to meet you
and you?
thankyou
1
2
3
4

head -n file

headの後に-nで数字を入力すると、先頭からn行を出力します。

$ head -5 test.txt
chaos and order
hello
hi
nice to meet you
and you?

tail file

headとは反対に、tailコマンドは末尾からテキストを表示します。

$ tail test.txt
thankyou
1
2
3
4
4
5
6
7
hihihihihi

tail -n file

-nを指定すると、末尾からn行を表示します。

$ tail -3 test.txt
6
7
hihihihihi

簡単なテキストを読むときや、どのようなテキストかを確認するときに、tail、headで手軽に確認すると便利です。