Change a string in a file with sed?

16,236

Solution 1

You don't need the grep.

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

Solution 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

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

Solution 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/'
Share:
16,236
ShreyasD
Author by

ShreyasD

Just trying to learn

Updated on June 04, 2022

Comments

  • ShreyasD
    ShreyasD almost 2 years

    I have a inputfile with template as shown below. I want to change the Version: using 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

    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