sed を使用したテキスト置換を行う
このステップでは、sed コマンドを使用したより高度なテキスト置換を探索します。
まず、「old」という単語が複数回出現する新しいサンプルファイルを作成しましょう。
echo "This is an old text. Replace the old text with new text." > sample.txt
単語のすべての出現箇所を置換する
単語のすべての出現箇所を置換するには、グローバルな g
フラグを使用します。
sed 's/old/new/g' sample.txt
出力例:
This is an new text. Replace the new text with new text.
最初の出現箇所のみを置換する
最初の出現箇所のみを置換するには、グローバルな g
フラグを省略します。
sed 's/old/new/' sample.txt
出力例:
This is an new text. Replace the old text with new text.
特定の行で置換する
特定の行でテキストを置換するには、s
コマンドの前に行番号を使用します。
sed '1s/old/new/' sample.txt
出力例:
This is an new text. Replace the old text with new text.
正規表現を使用して置換する
Sed は正規表現もサポートしています。正規表現を使用してテキストを置換するには、キャプチャされたグループを参照するために \1
構文を使用します。
sed 's/\(This.*\)old\(.*\)/\1new\2/' sample.txt
出力例:
This is an new text. Replace the new text with new text.
複数のファイルで置換する
複数のファイルでテキストを置換するには、ファイル名を引数として sed コマンドに渡します。
sed 's/old/new/g' sample.txt another_file.txt
これにより、sample.txt
と another_file.txt
の両方でテキスト置換が行われます。
次のステップでは、sed コマンドを使用して複数のファイルを編集する方法を学びます。