LoginSignup
13
12

More than 5 years have passed since last update.

[Tips]macのsedでファイル内容を一括置換

Last updated at Posted at 2017-08-31

若干直感的でなかったのでメモ。
mac(BSD)版の場合です。
LinuxなどのGNU版sedとは挙動が違う点があるので注意。

findの場合

$ find . -type f -print0 | xargs -0 sed -i '' -e 's/検索文字列/置換文字列/g'

ちなみにperlを使うとこんな感じ。
$ find . -type f -print | xargs perl -pi -e 's/検索文字列/置換文字列/g'

-iの後に''で空文字を指定するのがミソ。
sed -i -e 's/検索文字列/置換文字列/g'と書くと、hoge.txt-eのように意図しないバックアップファイルが生成される。
GNUの場合、''空文字は指定しなくてよい。

git grepの場合

普通のgrep、findだと対象のファイルを指定しないといけなかったりで面倒。
gitで管理しているリポジトリの中身だけでよければ、git grepが便利。.gitignoreしているファイルはもちろん無視される。

$ git grep -l '検索文字列' | xargs sed -i '' -e 's/検索文字列/置換文字列/g'

ちなみに、 git grep --no-indexとすれば、.gitignoreしているファイルやaddしていないファイルもgrepしてくれる。

13
12
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
13
12