高度な sed コマンドとパターンマッチング
これまでに sed
を使った基本的な置換と直接編集をマスターしました。では、もう少し高度な機能を探ってみましょう。
- 異なる区切り文字を使用する
- アドレス範囲を使用して特定の行を対象にする
- 複数のコマンドを組み合わせる
異なる区切り文字を使用する
これまで置換コマンドではスラッシュ /
を区切り文字として使用してきましたが、sed
では任意の文字を区切り文字として使用できます。これは、パターンや置換テキストにスラッシュが含まれる場合に特に便利です。
ファイルパスを含むファイルを作成しましょう。
echo "/usr/local/bin is in the PATH" > ~/project/paths.txt
echo "My config is in /etc/myapp/config.json" >> ~/project/paths.txt
/usr/local/bin
を /opt/bin
に置き換えたい場合、スラッシュを使用すると混乱する可能性があります。
sed 's/\/usr\/local\/bin/\/opt\/bin/' ~/project/paths.txt
その代わりに、#
などの異なる区切り文字を使用することができます。
sed 's#/usr/local/bin#/opt/bin#' ~/project/paths.txt
これははるかに読みやすくなります!出力は以下のようになるはずです。
/opt/bin is in the PATH
My config is in /etc/myapp/config.json
他の一般的な区切り文字には、|
、:
、_
などがあります。
アドレッシング - 特定の行を対象にする
sed
では、置換を適用する行を指定することができます。これは、コマンドの前にアドレスを付けることで行います。
行番号付きの新しいファイルを作成しましょう。
echo "Line 1: This is the first line." > ~/project/numbered.txt
echo "Line 2: This is the second line." >> ~/project/numbered.txt
echo "Line 3: This is the third line." >> ~/project/numbered.txt
echo "Line 4: This is the fourth line." >> ~/project/numbered.txt
echo "Line 5: This is the fifth line." >> ~/project/numbered.txt
3 行目の "line" を "row" に置き換えるには、次のようにします。
sed '3 s/line/row/' ~/project/numbered.txt
出力は以下のようになるはずです。
Line 1: This is the first line.
Line 2: This is the second line.
Line 3: This is the third row.
Line 4: This is the fourth line.
Line 5: This is the fifth line.
行の範囲を指定することもできます。2 行目から 4 行目の "line" を "row" に置き換えるには、次のようにします。
sed '2,4 s/line/row/' ~/project/numbered.txt
出力は以下のようになるはずです。
Line 1: This is the first line.
Line 2: This is the second row.
Line 3: This is the third row.
Line 4: This is the fourth row.
Line 5: This is the fifth line.
もう 1 つの便利な機能は、パターンに基づいて行をマッチさせることができることです。たとえば、"third" または "fourth" を含む行のみで "line" を "row" に置き換えるには、次のようにします。
sed '/\(third\|fourth\)/ s/line/row/' ~/project/numbered.txt
出力は以下のようになるはずです。
Line 1: This is the first line.
Line 2: This is the second line.
Line 3: This is the third row.
Line 4: This is the fourth row.
Line 5: This is the fifth line.
複数のコマンドを組み合わせる
-e
オプションを使用するか、コマンドをセミコロンで区切ることで、複数の sed
コマンドを組み合わせることができます。
1 つのコマンドで "first" を "1st"、"second" を "2nd"、"third" を "3rd" に置き換えましょう。
sed -e 's/first/1st/' -e 's/second/2nd/' -e 's/third/3rd/' ~/project/numbered.txt
あるいは、セミコロンを使用することもできます。
sed 's/first/1st/; s/second/2nd/; s/third/3rd/' ~/project/numbered.txt
どちらのコマンドも同じ出力を生成するはずです。
Line 1: This is the 1st line.
Line 2: This is the 2nd line.
Line 3: This is the 3rd line.
Line 4: This is the fourth line.
Line 5: This is the fifth line.
では、これらの変更を永続的にするために、次のようにします。
sed -i 's/first/1st/; s/second/2nd/; s/third/3rd/' ~/project/numbered.txt
そして、変更を確認します。
cat ~/project/numbered.txt
序数が更新されたテキストが表示されるはずです。