Linux 如何替换而不在sed中创建中间文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6889360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to substitute without creating intermediate file in sed?
提问by kingsmasher1
I was doing some hands-on with the Unix sed
command. I was trying out the substitution and append command, in a file. But the difficulty is, I have to create an intermediate file, and then do mv
to rename it to the original file.
我正在使用 Unixsed
命令进行一些实践。我正在一个文件中尝试替换和追加命令。但困难是,我必须创建一个中间文件,然后mv
将其重命名为原始文件。
Is there any way to do it at one shot in the same file?
有没有办法在同一个文件中一次性完成?
[root@dhcppc0 practice]# sed '1i\
> Today is Sunday
> ' file1 > file1
[root@dhcppc0 practice]# cat file1
[root@dhcppc0 practice]#
The file is deleted!
文件被删除!
[root@dhcppc0 practice]# sed 's/director/painter/' file1 > file1
[root@dhcppc0 practice]# cat file1
The file is deleted!
文件被删除!
采纳答案by Marcus Borkenhagen
GNU sed knows an option -i
which does in-placeedit of the given files.
GNU SED知道一个选项,-i
这确实就地给定文件的编辑。
When doing an operation file1 > file1
what actually happens is, that the file is openedand truncatedby the shell beforethe program (which gets it's name as argument) comes around reading anything from it.
在执行操作时file1 > file1
,实际发生的情况是,在程序(将其名称作为参数)读取文件之前,shell打开并截断了该文件。
Update:
更新:
sed's man page states the following on the -i
option (thanks Delan for mentioning it):
sed 的手册页在-i
选项中说明了以下内容(感谢 Delan 提到它):
-i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if extension supplied)
-i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if extension supplied)
回答by rorycl
sed -i.bak 's/director/painter/' file1
sed -i.bak 's/director/painter/' file1
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if extension supplied)
回答by dawnofthedead
Try this -
尝试这个 -
sed -i '' 's/originaltext/replacementtext/g' filename | cat filename
-i '' is meant for providing a backup file. If you are confident your replacement won't cause an issue you can put '' to pass no backup file
-i '' 用于提供备份文件。如果您确信您的替换不会引起问题,您可以将 '' 设置为不传递备份文件
/g is for replacing globally. If you have more than one originaltext in one line then with /g option will replace all else it will only replace the first.
/g 用于全局替换。如果一行中有多个原文,则使用 /g 选项将替换所有其他文本,它只会替换第一个。