あいつの日誌β

働きながら旅しています。

Linux や Mac のターミナルで複数ファイル一括置換する

いつも忘れるのメモ。

grep -rl '対象文字列"' ./* | xargs sed -i -e 's/対象文字列/置換したい文字列/g'

grep のオプションは以下の通り。下の階層も含めて対象文字列を含む ファイル名一覧を取得する

     -l, --files-with-matches
             Only the names of files containing selected lines are written to standard output.  grep will only search a file until a
             match has been found, making searches potentially less expensive.  Pathnames are listed once per file searched.  If the
             standard input is searched, the string ``(standard input)'' is written.
     -R, -r, --recursive
             Recursively search subdirectories listed.

sed のオプションは以下の通り。スクリプトs/対象文字列/置換したい文字列/g を実行して結果を同じファイルに上書きする

     -e command
             Append the editing commands specified by the command argument to the list of commands.

     -i extension
             Edit files in-place, saving backups with the specified extension.  If a zero-length extension is given, no backup will
             be saved.  It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or
             partial content in situations where disk space is exhausted, etc.