LoginSignup
1
0

More than 3 years have passed since last update.

論理ページごとに行番号をリセットしないnlコマンドのpオプション

Last updated at Posted at 2020-12-14

nlコマンドはpオプションを指定することで、行番号を論理ページにかかわらず通し番号にすることができます。

pオプションの使い方

オプションに追加の引数はありません。特筆することもありませんが、マニュアルを参照してみましょう。

info nl (GNU coreutils)

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

man nl (BSD)

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

POSIX

-p
Specify that numbering should not be restarted at logical page delimiters.

pオプションを試す

試してみましょう。

coreutils
$ echo -e 'a\n\:\:\nb'
a
\:\:
b
$ echo -e 'a\n\:\:\nb' | nl
     1  a

     1  b
$ echo -e 'a\n\:\:\nb' | nl -p
     1  a

     2  b
BSD
$ echo -e 'a\n\:\:\nb' | nl
     1  a
     1  b
$ echo -e 'a\n\:\:\nb' | nl -p
     1  a
     2  b

特に入力データが制御可能なケースでは、-pを利用する機会はほぼないでしょう。ボディに限った話であれば、以下のように区切り文字列を削除してしまうのと同じです。(厳密にはcoreutilsのnlにおいて空行に置き換わるかどうかの違いはありますが)

coreutils
$ echo -e 'a\n\:\:\nb' | sed 's/\\:\\://' |  nl
     1  a

     2  b
BSD
$ echo -e 'a\n\:\:\nb' | sed '/\\:\\:/d' | nl 
     1  a
     2  b

古いcoreutilsのnl(~v8.25)について

意外なことにcoreutilsのnlは初版から比較的最近まで正しく動作していませんでした。デフォルトの動作に問題があり常に-pが有効になった状態で、論理ページごとに行番号がリセットされることはありませんでした。これは2016年11月にリリースされたv8.26で修正されています。

coreutils~v8.25
$ echo -e 'a\n\:\:\nb' | nl
     1  a

     2  b
$ echo -e 'a\n\:\:\nb' | nl -p
     1  a

     2  b

サポートが継続されている主要なディストリビューションでも、RHEL 7がv8.22、Ubuntu 16.04LTSがv8.25の古いバージョンを採用しています。これらの環境のnlでは論理ページを含むデータから正しい行番号を得ることはできないので注意が必要です。
以前の記事で当たり前にリセットできるかのように書きましたが、お手元の環境でうまくいかない場合の原因はおそらくこの不具合によるものです。


1
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
1
0