cat コマンドの高度な機能
このステップでは、テキストファイルの操作をより効率的に行うための cat
コマンドのいくつかの便利な追加機能を探索します。
行番号の表示
cat
コマンドは、-n
オプションを使用して、ファイル内の各行に行番号を表示することができます。
## まだプロジェクトディレクトリにいない場合は移動する
cd ~/project
## 行番号付きで完全なメッセージを表示する
cat -n complete_message.txt
以下のような出力が表示されるはずです。
1 This is the first part of the message.
2 Followed by the second segment.
3 And this concludes the third and final part.
4 Additional data transmission received.
5 End of transmission.
この機能は、特定の行を参照する必要がある長いファイルを操作する際に特に便利です。
非表示文字の表示
時には、ファイルに特殊文字や非表示文字が含まれていることがあります。cat
コマンドには、これらの文字を可視化するためのオプションが用意されています。
-T
: タブ文字を ^I
として表示します。
-v
: 非表示文字を表示します。
-E
: 各行の末尾に $
を表示します。
特殊文字を含むファイルを作成し、それを表示してみましょう。
## タブと特殊文字を含むファイルを作成する
echo -e "Line with\ttab character\nAnother line" > special_chars.txt
## 特殊文字を可視化してファイルを表示する
cat -T special_chars.txt
出力:
Line with^Itab character
Another line
次に、行末文字を表示してみましょう。
## 行末マーカー付きで表示する
cat -E special_chars.txt
出力:
Line with tab character$
Another line$
対話的なファイル作成
cat
を使用して、対話的にファイルを作成することもできます。これは、テキストエディタを使用せずに小さなファイルを作成するのに便利です。
## 対話的に新しいファイルを作成する
cat > notes.txt
このコマンドを実行した後、以下の行を入力します。
Important notes:
1. Learn Linux commands
2. Practice file operations
3. Master redirection operators
入力が終了したら、Ctrl+D
を押します(これは入力の終了を示します)。
内容を確認してみましょう。
## メモファイルの内容を表示する
cat notes.txt
以下の内容が表示されるはずです。
Important notes:
1. Learn Linux commands
2. Practice file operations
3. Master redirection operators
複数の機能を組み合わせる
複数のオプションを組み合わせて、目的の出力を得ることができます。
## 行番号と行末マーカーを表示する
cat -n -E notes.txt
出力:
1 Important notes:$
2 1. Learn Linux commands$
3 2. Practice file operations$
4 3. Master redirection operators$
これらの高度な機能により、cat
コマンドは Linux でのテキストファイル操作において多用途のツールとなっています。