Change a string in a file with sed?

我怕爱的太早我们不能终老 提交于 2019-12-07 18:37:28

问题


I have a inputfile with template as shown below. I want to change the Version: using sed.

    Package: somename
    Priority: extra
    Section: checkinstall
    Maintainer: joe@example.com
    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

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/'

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


回答1:


You don't need the grep.

sed -i '/Version/s/3\.1\.0\.2-1/3.1.0.2/' <files>



回答2:


You want to use the "-i" switch to sed for "edit file [I]n place."

See sed man page: http://unixhelp.ed.ac.uk/CGI/man-cgi?sed




回答3:


The name sed literally comes from "Stream EDitor" - the behavior you're seeing is the way it was designed. When you say:

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 '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.




回答4:


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/'


来源:https://stackoverflow.com/questions/10919554/change-a-string-in-a-file-with-sed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!