Change a string in a file with sed?

2019-05-10 16:00发布

问题:

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


标签: linux sed awk gawk