前言

在 MacOS 下使用 sed -i 就会出现类似下面的错误

1
2
sed: 1: "...": command c expects \ followed by text
sed: 1: "...": command i expects \ followed by text

原因是由于 MacOS 下默认的 sed 和 Linux 下是不一样的,导致 -i 无法正确识别,通常的做法是安装一个 gnu-sed 已替换原本的 sed 命令

安装步骤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 查询一下
which sed

# 安装
brew install gnu-sed

# 查看
brew info gnu-sed

==> gnu-sed: stable 4.9 (bottled)
GNU implementation of the famous stream editor
https://www.gnu.org/software/sed/
Conflicts with:
ssed (because both install share/info/sed.info)
Installed
/opt/homebrew/Cellar/gnu-sed/4.9 (13 files, 616.5KB) *
Poured from bottle using the formulae.brew.sh API on 2024-08-23 at 16:14:00
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/g/gnu-sed.rb
License: GPL-3.0-or-later
==> Caveats
GNU "sed" has been installed as "gsed".
If you need to use it as "sed", you can add a "gnubin" directory
to your PATH from your bashrc like:

PATH="/opt/homebrew/opt/gnu-sed/libexec/gnubin:$PATH"


配置环境变量

PATH="/opt/homebrew/opt/gnu-sed/libexec/gnubin:$PATH" 部分配置到 ~/.zshrc 里面就可以了,别忘记 source 让它生效哦。

验证

1
2
3
4
# 记得验证一下
which sed

# 当然你也可以直接使用 `gsed`