Bash

Replace Text in Files with Bash sed Command

Introduces how to replace text in files using the Bash sed command. The -E command is necessary to enable reuse of group matches with \1. (Depending on the environment, you may need to use -ei instead of -Ei...

Shou Arisaka
1 min read
Nov 22, 2025

Introduces how to replace text in files using the Bash sed command.

$ cat > hoge.md
hoge
hogehoge
hoge
$ sed -Ei 's/^(hoge)/# \1/g' hoge.md
$ cat hoge.md
# hoge
# hogehoge
# hoge

Key point: The -E command is necessary to enable reuse of group matches with \1.

(Depending on the environment, you may need to use -ei instead of -Ei. Not sure.)

Use Case

To enable local network access in MySQL, you need to comment out bind-address in mysqld.cnf using vim mysqld.cnf. Letโ€™s automate this.

sudo cp /etc/mysql/mysql.conf.d/mysqld.cnf /etc/mysql/mysql.conf.d/mysqld.cnf.bak
sudo sed -Ei 's/^(bind-address)/# \1/g' hoge.md /etc/mysql/mysql.conf.d/mysqld.cnf

Share this article

Shou Arisaka Nov 22, 2025

๐Ÿ”— Copy Links