このページで解説している内容は、以下の YouTube 動画の解説で見ることができます。
【Linux】行数をつけて表示する:nlコマンド
nl コマンドの概要
「nl
」コマンドは、指定したファイルの各行に行番号を付けて表示するためのLinuxコマンドです。このコマンドは、通常のテキストファイルや標準入力からのテキストデータに対して、行番号を付加して表示します。これにより、ファイルの内容を確認しやすくなります。
【構文】nl [オプション] [ファイル名]
主なオプションと説明
オプション | 説明 |
---|---|
-b | 本文の行番号の付け方を指定します。STYLE には a (全行)、t (空行を除く全行)、n (番号を付けない)、pREGEXP (正規表現に一致する行)のいずれかを指定します。デフォルトは t 。 |
-i | 行番号の増分を指定します。デフォルトは 1 。 |
-n | 行番号のフォーマットを指定します。FORMAT には ln (左寄せ、ゼロパディングなし)、rn (右寄せ、ゼロパディングなし)、rz (右寄せ、ゼロパディングあり)のいずれかを指定します。 |
-s | 行番号とテキストの間のセパレータ文字列を指定します。デフォルトはタブ。 |
-v | 行番号の開始値を指定します。デフォルトは 1 。 |
コマンドの使用例と解説
1.準備作業
演習を行うためのテキストファイルを作成します。
・「nano file.txt
」コマンドを実行します。
nanoエディタを起動して、「file.txt」ファイルを作成します。
user01@ubuntu-vm:~$ nano file.txt
以下の内容を入力します。
This is the first line.
This is the third line.
This is the fourth line.
This is the seventh line.
入力したら、「Ctrl + O」キーを入力して「Enter」キーで保存、「Ctrl + X」キーでnanoエディタを終了させます。
2.基本的な使い方
・「nl file.txt
」コマンドを実行します。
「file.txt
」 の各行に行番号を付けて表示します。デフォルトでは、空行を除く全ての行に番号が付きます。
user01@ubuntu-vm:~$ nl file.txt
1 This is the first line.
2 This is the third line.
3 This is the fourth line.
4 This is the seventh line.
3.空行を除いて行番号を付ける。
・「nl -b t file.txt
」コマンドを実行します。
「file.txt
」の空行を除く全ての行に行番号を付けて表示します。これはデフォルトの動作です。
user01@ubuntu-vm:~$ nl -b t file.txt
1 This is the first line.
2 This is the third line.
3 This is the fourth line.
4 This is the seventh line.
4.全ての行に行番号を付ける。
・「nl -b a file.txt
」コマンドを実行します。
「file.txt
」の全ての行に行番号を付けて表示します。
user01@ubuntu-vm:~$ nl -b a file.txt
1 This is the first line.
2
3 This is the third line.
4 This is the fourth line.
5
6
7 This is the seventh line.
5.行番号をゼロパディングして表示
・「nl -n rz file.txt
」コマンドを実行します。
「file.txt
」行番号を右寄せでゼロパディングして表示します。例えば、行番号が 000001
、000002
という形式になります。
user01@ubuntu-vm:~$ nl -n rz file.txt
000001 This is the first line.
000002 This is the third line.
000003 This is the fourth line.
000004 This is the seventh line.
6.行番号の増分を2に設定
・「nl -i 2 file.txt
」コマンドを実行します。
「file.txt
」行番号を2ずつ増加させて表示します。行番号は 1, 3, 5,...
のように増加します。
user01@ubuntu-vm:~$ nl -i 2 file.txt
1 This is the first line.
3 This is the third line.
5 This is the fourth line.
7 This is the seventh line.
7.行番号の開始値を10に設定
・「nl -v 10 file.txt
」コマンドを実行します。
「file.txt
」行番号の開始値を 10
に設定して表示します。
user01@ubuntu-vm:~$ nl -v 10 file.txt
10 This is the first line.
11 This is the third line.
12 This is the fourth line.
13 This is the seventh line.
8.行番号とテキストの間のセパレータをカスタマイズ
・「nl -s " | " file.txt
」コマンドを実行します。
「filen.txt
」行番号とテキストの間に " | "
をセパレータとして挿入します。
user01@ubuntu-vm:~$ nl -s " | " file.txt
1 | This is the first line.
2 | This is the third line.
3 | This is the fourth line.
4 | This is the seventh line.
9.演習で作成したファイルの削除
演習で使用したファイルを削除します。
・「rm file.txt
」コマンドを実行し、「ls」コマンドで削除されたかどうかを確認します。
user01@ubuntu-vm:~$ rm file.txt
user01@ubuntu-vm:~$ ls
snap テンプレート ドキュメント ピクチャ 公開
ダウンロード デスクトップ ビデオ ミュージック
まとめ
これらの使用例を通じて、「nl
」コマンドを使うことで、ファイルの内容を整理しやすく確認することができることが分かります。行番号付きの出力は、スクリプトのデバッグやコードレビュー、データ解析など多くの場面で役立ちます。