LoginSignup
2
0

More than 3 years have passed since last update.

sedの"&"の挙動で罠にハマった話。

Last updated at Posted at 2020-12-19

ハマったこと

sedで & を含む文字に置換しようとする場合は一手間必要です。

REPLACE_TARGET_STRING123&456に置換する場合を考えます。

cat replace.txt
REPLACE_TARGET_STRING

普通にsedを実行すると下記のような出力結果となり、意図した結果となりません。

sed -e "s@REPLACE_TARGET_STRING@123&456@g" replace.txt
123REPLACE_TARGET_STRING456

というのも、sedの 置換後文字列 の中に & が存在する場合、これは置換前の文字列(この場合、REPLACE_TARGET_STRING)に置き換えられます。(知らなかった)

❯ man sed
(略)
             An ampersand (``&'') appearing in the replacement is replaced by
             the string matching the RE.  The special meaning of ``&'' in this
             context can be suppressed by preceding it by a backslash.

バックスラッシュをつけてエスケープすることで、意図した結果を得ることができます。

❯ sed -e "s@REPLACE_TARGET_STRING@123\&456@g" replace.txt
123&456

知っている人も多い気がしますが、僕は全然知らなかったのでメモ。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0