nl コマンドは、テキストファイルや標準入力の各行に自動で行番号を付与して出力するためのコマンドです。
ソースコードやログファイルの一部を確認する際に、行数を見やすくする用途で利用されます。
構文(Syntax)
nl [オプション] [FILE...]
主なオプション一覧
| オプション | 説明 | 使用例 |
|---|---|---|
-b a | すべての行に番号を付ける | nl -b a sample.txt |
-b t | 空行を除いた行に番号を付ける(デフォルト) | nl -b t sample.txt |
-n ln | 行番号を左寄せ表示 | nl -n ln sample.txt |
-n rn | 行番号を右寄せ表示(デフォルト) | nl -n rn sample.txt |
-n rz | 行番号を0で埋めて右寄せ表示 | nl -n rz sample.txt |
-w N | 行番号の桁数を指定 | nl -w 4 sample.txt |
-s STRING | 行番号とテキストの区切り文字列を指定 | `nl -s “ |
-v N | 行番号の開始値を指定 | nl -v 10 sample.txt |
-i N | 行番号の増分を指定 | nl -i 5 sample.txt |
実行例
すべての行に番号を付与
nl -b a sample.txt
出力例:
1 line one
2
3 line three
空行を除外して番号を付与(デフォルト)
nl sample.txt
出力例:
1 line one
2 line three
行番号を4桁・ゼロ埋めで表示
nl -n rz -w 4 sample.txt
出力例:
0001 line one
0002
0003 line three
区切り文字をカスタマイズ
nl -s " | " sample.txt
出力例:
1 | line one
2 |
3 | line three
エラー例(存在しないファイルを指定)
nl notfound.txt
出力例:
nl: notfound.txt: No such file or directory
関連コマンド
cat: ファイル内容を表示する基本コマンド。-nで行番号付き出力も可能。less: ファイルをページ送りで表示。オプションで行番号も表示できる。awk: 行番号を制御しながら出力する処理が可能。
備考
- GNU Coreutils に含まれるコマンドで、環境によってはオプションが異なる場合があります(BSD系では挙動が異なる)。
- 一般ユーザー権限で利用でき、特別な権限は不要です。
/etc/passwdなどのシステムファイルを読む際も、読み取り権限さえあればnlで行番号付きで出力可能です。
参考
- manページ: https://man7.org/linux/man-pages/man1/nl.1.html
- GNU Coreutils公式: https://www.gnu.org/software/coreutils/

コメント