Linux 使用 sed 更改文件中的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10919554/
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
Change a string in a file with sed?
提问by ShreyasD
I have a inputfile with template as shown below. I want to change the Version: using sed.
我有一个带有模板的输入文件,如下所示。我想更改版本:使用 sed。
Package: somename
Priority: extra
Section: checkinstall
Maintainer: [email protected]
Architecture: i386
Version: 3.1.0.2-1
Depends:
Provides: somename
Description: some description
Currently I am getting the current version using grep -m 1 Version inputfile | sed 's/[:_#a-zA-Z\s"]*//g'
and I am trying to replace the current version with sed 's/3.1.0.2-1/3.1.0.2/' inputfile
目前我正在使用当前版本grep -m 1 Version inputfile | sed 's/[:_#a-zA-Z\s"]*//g'
,我正在尝试用sed 's/3.1.0.2-1/3.1.0.2/' inputfile
However this does not seem to work, but when I try it in command line using echo it works.
echo 'Version: 3.0.9.1' | sed 's/3.0.9.1/3.2.9.2/'
但是,这似乎不起作用,但是当我使用 echo 在命令行中尝试它时,它起作用了。
echo 'Version: 3.0.9.1' | sed 's/3.0.9.1/3.2.9.2/'
Output: Version: 3.2.9.2
Any help on how I can accomplish this would be appreciated. Preferably I would like to change the version without getting the current version in the file.
任何有关我如何实现这一目标的帮助将不胜感激。最好我想更改版本而不在文件中获取当前版本。
Thanks In Advance
提前致谢
采纳答案by Diego Torres Milano
You don't need the grep.
你不需要grep。
sed -i '/Version/s/3\.1\.0\.2-1/3.1.0.2/' <files>
回答by Eric
You have a typo, the last dot should be a dash, try this:
你有一个错字,最后一个点应该是一个破折号,试试这个:
sed 's/3.1.0.2-1/3.1.0.2-2/'
回答by twalberg
The name sed
literally comes from "Stream EDitor" - the behavior you're seeing is the way it was designed. When you say:
这个名字sed
字面上来自“流编辑器”——你看到的行为就是它的设计方式。当你说:
sed 'some commands' file
it reads the file, executes the commands and prints the result - it doesn't save it back to the file (although some versions of sed
have some options to tell it to do that). You probably want to do this:
它读取文件,执行命令并打印结果 - 它不会将其保存回文件(尽管某些版本sed
有一些选项可以告诉它这样做)。你可能想要这样做:
sed 'some commands' file > newfile
Then verify that newfile
is correct, and then mv newfile file
. If you're absolutely certain your edit script is correct, and you can deal with the consequences of overwriting your file with wrong data if they're not, then you might consider using the in-place editing flags, but it's generally safer to save to a temporary file so you can test/validate.
然后验证newfile
是否正确,然后mv newfile file
. 如果您绝对确定您的编辑脚本是正确的,并且您可以处理用错误数据覆盖文件的后果,如果它们不是,那么您可以考虑使用就地编辑标志,但通常保存更安全到一个临时文件,以便您可以测试/验证。
回答by Andrew Tomazos
You want to use the "-i" switch to sed for "edit file [I]n place."
您想使用“-i”开关将 sed 用于“编辑文件 [I]n 位置”。
See sed man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?sed
请参阅 sed 手册页:http: //unixhelp.ed.ac.uk/CGI/man-cgi?sed