管理人Kのひとりごと

デジモノレビューやプログラミングや写真など

sedで複数ファイルの中身を一括置換

sedで複数ファイルの中身を一括置換する方法をメモ。

Powershellで同じことをやってみました↓
www.k-hitorigoto.online

確認環境

[root@da4099ac13ae replace_test]# cat /etc/redhat-release
CentOS Linux release 7.8.2003 (Core)

[root@da4099ac13ae /]# sed --version
sed (GNU sed) 4.2.2

複数ファイルの中身を一括置換

# 処理対象ファイル確認
[root@da4099ac13ae replace_test]# find ./ -type f -name "*.txt" | xargs head
==> ./one.txt <==
first
second
third

==> ./two.txt <==
first
second
third

==> ./three.txt <==
first
second
third

# 処理実施
# *.txtのファイルそれぞれに対し、「first」を「FIRST」に置換して上書き保存する
# -i : ファイルを上書き
# s/first/FIRST : firstをFIRSTに置換
[root@da4099ac13ae replace_test]# sed -i s/first/FIRST/ *.txt

# 処理結果確認
[root@da4099ac13ae replace_test]# find ./ -type f -name "*.txt" | xargs head
==> ./one.txt <==
FIRST
second
third

==> ./two.txt <==
FIRST
second
third

==> ./three.txt <==
FIRST
second
third

参考にしました