我试图找出是否可以在单个sed命令中编辑一个文件,而无需手动将编辑的内容流到一个新文件中,然后将新文件重命名为原始文件名。

我尝试了-i选项,但是Solaris系统说-i是非法选项。还有别的办法吗?


当前回答

在一个系统中,sed没有编辑文件的能力,我认为更好的解决方案是使用perl:

perl -pi -e 's/foo/bar/g' file.txt

虽然这确实创建了一个临时文件,但它替换了原始文件,因为已经提供了一个空的就地后缀/扩展名。

其他回答

你可以使用vi

vi -c '%s/foo/bar/g' my.txt -c 'wq'

下面的程序在我的mac上运行良好

sed -i.bak 's/foo/bar/g' sample

在示例文件中,我们用bar替换foo。原始文件的备份将保存在sample.bak中

要编辑内联而不备份,请使用以下命令

sed -i'' 's/foo/bar/g' sample

如果您正在替换相同数量的字符,并且在仔细阅读“就地”编辑文件后……

您还可以使用重定向操作符<>打开文件进行读写:

sed 's/foo/bar/g' file 1<> file

现场观看:

$ cat file
hello
i am here                           # see "here"
$ sed 's/here/away/' file 1<> file  # Run the `sed` command
$ cat file
hello
i am away                           # this line is changed now

从Bash参考手册→3.6.10打开文件描述符读写:

重定向操作符 [n] < >词 使文件名为word展开的文件被打开 在文件描述符n或文件描述符0上进行读写 如果未指定n。如果该文件不存在,则创建该文件。

为了在Mac上解决这个问题,我不得不在core-utils中添加一些unix函数。

brew install grep
==> Caveats
All commands have been installed with the prefix "g".
If you need to use these commands with their normal names, you
can add a "gnubin" directory to your PATH from your bashrc like:
  PATH="/usr/local/opt/grep/libexec/gnubin:$PATH"

使用gsed而不是sed调用。mac默认不喜欢grep -rl显示带有。/前缀的文件名。

~/my-dir/configs$ grep -rl Promise . | xargs sed -i 's/Promise/Bluebird/g'

sed: 1: "./test_config.js": invalid command code .

我还必须使用xargs -I{} sed -I 's/Promise/Bluebird/g'{}来处理名称中有空格的文件。

就像《007:大破天幕杀机》中Moneypenny说的:“有时候旧的方法是最好的。” 金凯德后来也说过类似的话。

$ printf ',s/false/true/g\nw\n' | ed {YourFileHere}

快乐编辑到位。 增加了'\nw\n'来写入文件。很抱歉没有及时回复请求。