⚠️ 記事内に広告を含みます。

sedコマンドと正規表現を使って置換・行削除する方法

sedコマンドの使い方

sedコマンドは指定したテキストを削除したり、別の文字に置換したりすることができるコマンドです。

/

sedコマンドの使用例

・特定の部分のコメントを全て削除したい

・設定ファイルを流用した時に設定ファイル中のドメイン名を別のものに変更したい

よく使用するコマンドなので使い方を覚えておくと良いです

文字列を置換する

sedでは指定した文字列を置換することができます。

$ cat txt
this is the test

$ sed 's/this/That/g' txt
That is the test

標準出力をパイプでsedに渡す方法もよく使います
$ cat txt | sed 's/this/That/g'
That is the test

どちらの方法でも元のファイルには影響がありません。
$ cat txt
this is the test

ちなみに区切り文字/は別のものでもよい
$ cat txt | sed 's,this,That,g'
That is the test
置換したい文字列中に/を使ってれば別の区切り文字を指定したほうが良い

末尾のフラグgは行中にマッチするものが複数ある場合も全て置換するという意味です。最初にマッチした一行目だけ置換するという意味ではありません。

$ cat txt | sed -e 's/test/hello/'
this is the hello1 test1 →2つめのtestは置換されてない
this is the hello2 test2 →2行目も最初のtestは置換されている
#this is the hello*

フラグgを設定 → 2番目に登場するtestも置換されている
$ cat txt | sed -e 's/test/hello/g'
this is the hello1 hello1
this is the hello2 hello2
#this is the hello*

シングルクオートについて

$ cat txt | sed s/this/That/g
That is the test

文字列を変更
$ cat txt
#this is the test*

特殊文字の*は置換されていない
$ cat txt | sed s/test\*/hello/g
#this is the hello*

シングルクオートを入れると文字列として認識される
$ cat txt | sed 's/test\*/hello/g'
#this is the hello

正規表現で指定する

sedは正規表現が使えます。

$ cat txt
this is the test1 test1
this is the test2 test2
#this is the test*

t〇〇〇に当てはまるものを置換(thisとtest)→the(空白)もマッチして置換されてしまっている
$ cat txt | sed -e 's/t.../hello/g'
hello is hellohello1 hello1
hello is hellohello2 hello2
#hello is hellohello*

正規表現で空白以外の一文字に変更してthe(空白)が置換されないようにする
$ cat txt | sed -e 's/t..[^ ]/hello/g'
hello is the hello1 hello1
hello is the hello2 hello2
#hello is the hello*

他のオプションについて

上書き保存 i

sedでファイルを直接開いたときに変更内容を保存したい場合はiオプションを使います

$ sed -i 's/this/That/g' txt
That is the test

複数のパターンを指定する

-eで複数のパターンを記述する

$ cat txt | sed -e 's/this/It/g' -e 's/the/a/g'
It is a test1 test1
It is a test2 test2
#It is a test*

行番号指定で行を削除する

dは削除を意味する。

1行目と3行目を削除
$ cat txt | sed -e '1d' -e '3d'
this is the test2 test2

1~2行目を削除
$ cat txt | sed -e '1,2d'
#this is the test*

正規表現でマッチする行を削除
$ cat txt | sed -e '/test1/d'
this is the test2 test2
#this is the test*

これはgrepを使ってもできる
$ cat txt | grep -v test1
this is the test2 test2
#this is the test*

指定文字列の後に改行を入れる

特定の文字列の後に改行を追加したい場合もsedが使えます。

下記のファイルのAgeの行の下に改行を入れたいとします。

Name Taro
ZIP Tokyo Shinjuku-ku Nishishinjuku
Age 23
Name Kosaka
ZIP Hokkaido Sapporo-shi Kita-ku kita
Age 37

sedのオプション-Eを使って拡張正規表現を使い、置換前の()の中身を\1として置換後に指定してその後に改行(¥n)を追加します。

意味が良くわからないと思うので下記の例をみてください。

# cat customer.txt | sed -E 's/^(Age.*)/\1\n/'

Name Taro
ZIP Tokyo Shinjuku-ku Nishishinjuku
Age 23

Name Kosaka
ZIP Hokkaido Sapporo-shi Kita-ku kita
Age 37

#

置換前のAge.*はAge 23やAge 37にマッチする正規表現です。
これを丸括弧()で囲むことで(Age.*)を一つのグループとして認識させます。

次に置換後にある\1は置換前の1つ目の()の中身を表します。
つまり、ここではAge.*であり、上の例ではAge 23, Age 37を指しています。

したがって、\1\nが意味するのはAge 23, Age 37の後に改行を入れろという意味になります。
このAge .*の後に改行 \n を加えるという意味になります。(先頭の^はaaa Age 37等をマッチさせないため)

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です