0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

nlコマンドAdvent Calendar 2020

Day 3

nlコマンドの使い方を調べる

Last updated at Posted at 2020-12-02

Unix系のコマンドライン環境には、様々なマニュアルがシステム上に備わっています。この記事では、nlコマンドの使い方をコマンドの機能を用いて調べる方法を説明していきます。実際のnlの使い方については次回以降の記事で説明していく予定です。

マニュアルの表示方法

--helpオプション

一番簡単に参照できるのは、コマンドのオプションにあるヘルプ(Usage)を見ることです。実装によってはヘルプがない場合もあります。

※”▶”の行をクリックすると実行結果が表示されます

`$ nl --help` #GNU coreutils
coreutils
Usage: gnl [OPTION]... [FILE]...
Write each FILE to standard output, with line numbers added.

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

Mandatory arguments to long options are mandatory for short options too.
  -b, --body-numbering=STYLE      use STYLE for numbering body lines
  -d, --section-delimiter=CC      use CC for logical page delimiters
  -f, --footer-numbering=STYLE    use STYLE for numbering footer lines
  -h, --header-numbering=STYLE    use STYLE for numbering header lines
  -i, --line-increment=NUMBER     line number increment at each line
  -l, --join-blank-lines=NUMBER   group of NUMBER empty lines counted as one
  -n, --number-format=FORMAT      insert line numbers according to FORMAT
  -p, --no-renumber               do not reset line numbers for each section
  -s, --number-separator=STRING   add STRING after (possible) line number
  -v, --starting-line-number=NUMBER  first line number for each section
  -w, --number-width=NUMBER       use NUMBER columns for line numbers
      --help     display this help and exit
      --version  output version information and exit

Default options are: -bt -d'\:' -fn -hn -i1 -l1 -n'rn' -s<TAB> -v1 -w6

CC are two delimiter characters used to construct logical page delimiters;
a missing second character implies ':'.

STYLE is one of:

  a      number all lines
  t      number only nonempty lines
  n      number no lines
  pBRE   number only lines that contain a match for the basic regular
         expression, BRE

FORMAT is one of:

  ln     left justified, no leading zeros
  rn     right justified, no leading zeros
  rz     right justified, leading zeros


GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Report any translation bugs to <https://translationproject.org/team/>
Full documentation <https://www.gnu.org/software/coreutils/nl>
or available locally via: info '(coreutils) nl invocation'

coreutilsのnlでは、使えるオプションの一覧などを簡潔に表示してくれます。しかし、BSD系のnlでは、エラーメッセージ「nl: illegal option -- -」が先頭に表示されます。

$ nl --help #*BSD(macOS)

*BSD(macOS)
nl: illegal option -- -
usage: nl [-p] [-b type] [-d delim] [-f type] [-h type] [-i incr] [-l num]
          [-n format] [-s sep] [-v startnum] [-w width] [file]

結果的にヘルプは表示されていますが、--helpオプションが実装されておらず間違った使い方だと認識されています。そのため親切に有効なオプションを同時に表示してくれているというわけです。

Manpage

前回の記事でも軽く触れましたが、ManpageはUnix系のシステムで最も一般的なマニュアルの確認方法です。コマンドだけでなく様々な情報をまとめています。例えば他のカテゴリにも同一名の項目がある場合には、セクション番号を指定して区別する必要があります。コマンドのセクション番号は1です。たとえば、printf1でコマンド、3でC言語の関数についての説明を読むことができman 3 printfのようにセクション番号を指定します。Manpageのページャはlessと同じ操作で扱うことができますので、スペースでページ送り、qで終了できます。

`$ man nl` #GNU coreutils
coreutils
NL(1)                            User Commands                           NL(1)



NAME
       nl - number lines of files

SYNOPSIS
       nl [OPTION]... [FILE]...

DESCRIPTION
       Write each FILE to standard output, with line numbers added.

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

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

       -b, --body-numbering=STYLE
              use STYLE for numbering body lines

       -d, --section-delimiter=CC
              use CC for logical page delimiters

       -f, --footer-numbering=STYLE
              use STYLE for numbering footer lines

       -h, --header-numbering=STYLE
              use STYLE for numbering header lines

       -i, --line-increment=NUMBER
              line number increment at each line

       -l, --join-blank-lines=NUMBER
              group of NUMBER empty lines counted as one

       -n, --number-format=FORMAT
              insert line numbers according to FORMAT

       -p, --no-renumber
              do not reset line numbers for each section

       -s, --number-separator=STRING
              add STRING after (possible) line number

       -v, --starting-line-number=NUMBER
              first line number for each section

       -w, --number-width=NUMBER
              use NUMBER columns for line numbers

       --help display this help and exit

       --version
              output version information and exit

       Default options are: -bt -d'\:' -fn -hn -i1 -l1 -n'rn' -s<TAB> -v1 -w6

       CC are two delimiter characters used to construct logical  page  delim-
       iters; a missing second character implies ':'.

       STYLE is one of:

       a      number all lines

       t      number only nonempty lines

       n      number no lines

       pBRE   number  only  lines  that  contain a match for the basic regular
              expression, BRE

       FORMAT is one of:

       ln     left justified, no leading zeros

       rn     right justified, no leading zeros

       rz     right justified, leading zeros

AUTHOR
       Written by Scott Bartram and David MacKenzie.

REPORTING BUGS
       GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
       Report any translation bugs to <https://translationproject.org/team/>

COPYRIGHT
       Copyright (C) 2020 Free Software Foundation, Inc.  License GPLv3+:  GNU
       GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
       This  is  free  software:  you  are free to change and redistribute it.
       There is NO WARRANTY, to the extent permitted by law.

SEE ALSO
       Full documentation <https://www.gnu.org/software/coreutils/nl>
       or available locally via: info '(coreutils) nl invocation'



GNU coreutils 8.32                March 2020                             NL(1)
`$ man nl` #BSD(macOS)
*BSD(macOS)
NL(1)                     BSD General Commands Manual                    NL(1)

NAME
     nl -- line numbering filter

SYNOPSIS
     nl [-p] [-b type] [-d delim] [-f type] [-h type] [-i incr] [-l num]
        [-n format] [-s sep] [-v startnum] [-w width] [file]

DESCRIPTION
     The nl utility reads lines from the named file or the standard input if
     the file argument is omitted, applies a configurable line numbering fil-
     ter operation and writes the result to the standard output.

     The nl utility treats the text it reads in terms of logical pages.
     Unless specified otherwise, line numbering is reset at the start of each
     logical page.  A logical page consists of a header, a body and a footer
     section; empty sections are valid.  Different line numbering options are
     independently available for header, body and footer sections.

     The starts of logical page sections are signalled by input lines contain-
     ing nothing but one of the following sequences of delimiter characters:

           Line      Start of
           \:\:\:    header
           \:\:      body
           \:        footer

     If the input does not contain any logical page section signalling direc-
     tives, the text being read is assumed to consist of a single logical page
     body.

     The following options are available:

     -b type      Specify the logical page body lines to be numbered.  Recog-
                  nized type arguments are:

                  a       Number all lines.

                  t       Number only non-empty lines.

                  n       No line numbering.

                  pexpr   Number only those lines that contain the basic regu-
                          lar expression specified by expr.

                  The default type for logical page body lines is t.

     -d delim     Specify the delimiter characters used to indicate the start
                  of a logical page section in the input file.  At most two
                  characters may be specified; if only one character is speci-
                  fied, the first character is replaced and the second charac-
                  ter remains unchanged.  The default delim characters are
                  ``\:''.

     -f type      Specify the same as -b type except for logical page footer
                  lines.  The default type for logical page footer lines is n.

     -h type      Specify the same as -b type except for logical page header
                  lines.  The default type for logical page header lines is n.

     -i incr      Specify the increment value used to number logical page
                  lines.  The default incr value is 1.

     -l num       If numbering of all lines is specified for the current logi-
                  cal section using the corresponding -b a, -f a or -h a
                  option, specify the number of adjacent blank lines to be
                  considered as one.  For example, -l 2 results in only the
                  second adjacent blank line being numbered.  The default num
                  value is 1.

     -n format    Specify the line numbering output format.  Recognized format
                  arguments are:
                  ln      Left justified.
                  rn      Right justified, leading zeros suppressed.
                  rz      Right justified, leading zeros kept.

                  The default format is rn.

     -p           Specify that line numbering should not be restarted at logi-
                  cal page delimiters.

     -s sep       Specify the characters used in separating the line number
                  and the corresponding text line.  The default sep setting is
                  a single tab character.

     -v startnum  Specify the initial value used to number logical page lines;
                  see also the description of the -p option.  The default
                  startnum value is 1.

     -w width     Specify the number of characters to be occupied by the line
                  number; in case the width is insufficient to hold the line
                  number, it will be truncated to its width least significant
                  digits.  The default width is 6.

ENVIRONMENT
     The LANG, LC_ALL, LC_CTYPE and LC_COLLATE environment variables affect
     the execution of nl as described in environ(7).

EXIT STATUS
     The nl utility exits 0 on success, and >0 if an error occurs.

SEE ALSO
     jot(1), pr(1)

STANDARDS
     The nl utility conforms to IEEE Std 1003.1-2001 (``POSIX.1'').

HISTORY
     The nl utility first appeared in AT&T System V Release 2 UNIX.

BUGS
     Input lines are limited to LINE_MAX (2048) bytes in length.

BSD                            January 26, 2005                            BSD

Texinfo

GNUのコマンドユーティリティであるcoreutilsは、公式のマニュアルとしてTexinfoというものがあります。GNUは情報提供方法としてTexinfoを推奨しているため、Manpageの記述はcoreutilsの開発メンバーによって直接メンテナンスされていません。LinuxではLinux man-page projectが内容の更新を担っています。詳しい説明を参照する場合には、オリジナルのTexinfoを閲覧するほうが良いでしょう。man同様にinfoで各コマンドの説明を表示できます。ページャにはEmacsが使われるため、操作には少々慣れが必要です。スペースでページ送り、Ctrl-x Ctrl-cで終了できます。

`$ info nl` #GNU coreutils
coreutils
File: coreutils.info,  Node: nl invocation,  Next: od invocation,  Prev: tac invocation,  Up: Output of entire files

3.3 ‘nl’: Number lines and write files
======================================

‘nl’ writes each FILE (‘-’ means standard input), or standard input if
none are given, to standard output, with line numbers added to some or
all of the lines.  Synopsis:

     nl [OPTION]... [FILE]...

   ‘nl’ decomposes its input into (logical) page sections; by default,
the line number is reset to 1 at each logical page section.  ‘nl’ treats
all of the input files as a single document; it does not reset line
numbers or logical pages between files.

   A logical page consists of three sections: header, body, and footer.
Any of the sections can be empty.  Each can be numbered in a different
style from the others.

   The beginnings of the sections of logical pages are indicated in the
input file by a line containing exactly one of these delimiter strings:

‘\:\:\:’
     start of header;
‘\:\:’
     start of body;
‘\:’
     start of footer.

   The two characters from which these strings are made can be changed
from ‘\’ and ‘:’ via options (see below), but the pattern and length of
each string cannot be changed.

   A section delimiter is replaced by an empty line on output.  Any text
that comes before the first section delimiter string in the input file
is considered to be part of a body section, so ‘nl’ treats a file that
contains no section delimiters as a single body section.

   The program accepts the following options.  Also see *note Common
options::.

‘-b STYLE’
‘--body-numbering=STYLE’
     Select the numbering style for lines in the body section of each
     logical page.  When a line is not numbered, the current line number
     is not incremented, but the line number separator character is
     still prepended to the line.  The styles are:

     ‘a’
          number all lines,
     ‘t’
          number only nonempty lines (default for body),
     ‘n’
          do not number lines (default for header and footer),
     ‘pBRE’
          number only lines that contain a match for the basic regular
          expression BRE.  *Note Regular Expressions: (grep)Regular
          Expressions.

‘-d CD’
‘--section-delimiter=CD’
     Set the section delimiter characters to CD; default is ‘\:’.  If
     only C is given, the second remains ‘:’.  (Remember to protect ‘\’
     or other metacharacters from shell expansion with quotes or extra
     backslashes.)

‘-f STYLE’
‘--footer-numbering=STYLE’
     Analogous to ‘--body-numbering’.

‘-h STYLE’
‘--header-numbering=STYLE’
     Analogous to ‘--body-numbering’.

‘-i NUMBER’
‘--line-increment=NUMBER’
     Increment line numbers by NUMBER (default 1).

‘-l NUMBER’
‘--join-blank-lines=NUMBER’
     Consider NUMBER (default 1) consecutive empty lines to be one
     logical line for numbering, and only number the last one.  Where
     fewer than NUMBER consecutive empty lines occur, do not number
     them.  An empty line is one that contains no characters, not even
     spaces or tabs.

‘-n FORMAT’
‘--number-format=FORMAT’
     Select the line numbering format (default is ‘rn’):

     ‘ln’
          left justified, no leading zeros;
     ‘rn’
          right justified, no leading zeros;
     ‘rz’
          right justified, leading zeros.

‘-p’
‘--no-renumber’
     Do not reset the line number at the start of a logical page.

‘-s STRING’
‘--number-separator=STRING’
     Separate the line number from the text line in the output with
     STRING (default is the TAB character).

‘-v NUMBER’
‘--starting-line-number=NUMBER’
     Set the initial line number on each logical page to NUMBER (default
     1).

‘-w NUMBER’
‘--number-width=NUMBER’
     Use NUMBER characters for line numbers (default 6).

   An exit status of zero indicates success, and a nonzero value
indicates failure.

コマンドの互換性

これまで見てきたとおり、主要な実装においてnlは11個のオプションをサポートします。そしてオプションの文字も実装によらず同じものが利用されています。これはPOSIXというIEEEの標準規格によって、コマンドのインターフェースがある程度決められ互換性が維持されているからです。標準化されているおかげで、私たちはどの環境にあるコマンドでもほとんど同じ操作で使用することができるのです。
しかし実際には実装による差も少なからず存在します。それらについても以降の記事で触れていく予定です。


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?