Published on

Linux head, tail 명령어 기초

Authors
  • Name
    Twitter

Overview

Linux 에는 headtail 이라는 유용한 도구가 있습니다. 이를 활용하면 text 파일에서 앞부분이나 뒷부분을 확인할 수 있습니다.

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 명령어는 뒤에서부터 text를 보여줍니다.

$ 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

간단한 text를 읽을 때, 또는 어떤 text인지 볼 때 tail, head로 편하게 확인하면 유용할 것 같습니다.