---
title: "(转)mac os下sed来进行文件内容的替换操作"
author: "7090"
date: "2016-10-14T11:26:29Z"
tags: []
categories: ["操作系统"]
slug: "mac-os-sed"
draft: false
lastmod: "2016-10-14T11:26:29Z"
id: 2330538
url: "https://7090.iteye.com/blog/2330538"
---

在mac osx lion中sed来进行文件内容的替换操作，使用命令为：


```os
sed -i 's/oldstring/newstring/g' full-path-file
```

执行后提示出错，错误信息为：“sed: 1: command a expects \ followed by text”，但是相同的命令拿到centos下确能执行成功。 使用man查看命令的参数详细说明，两个系统下对参数“i”的要求不一样。
mac osx中为：


```os
-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.
centos中为：

-i[suffix], --in-place[=suffix]
  edit files in place (makes backup if extension supplied)
```


参数“i”的用途是直接在文件中进行替换。为防止误操作带来灾难性的后果，sed在替换前可以自动对文件进行备份，前提是需要提供一个后缀名。从上面对参数“i”的详细说明中可以看到，mac osx下是强制要求备份的（当然也可以使用空字符串来取消备份），但centos下是可选的。

如果不需要备份文件，mac osx下可以使用如下命令完成替换操作：

```os
sed -i '' 's/oldstring/newstring/g' full-path-file
```



例子：

```os
cd /tmp
echo "netingcn.com" > sed_test.txt
cat sed_test.txt
sed -i '' 's/netingcn/www\.netingcn/g' sed_test.txt
cat sed_test.txt
rm -rf sed_test.txt
cd -
```


转：http://www.netingcn.com/mac-osx-sed-command-expects-followed-by-text.html