sed not replacing lines

13,263

Solution 1

Sed operates on streams and prints its output to standard out.

It does not modify the input file.

It's typically used like this when you want to capture its output in a file:

#
# replace every occurrence of foo with bar in input-file
#
sed 's/foo/bar/g' input-file > output-file

The above command invokes sed on input-file and redirects the output to a new file named output-file.

Depending on your platform, you might be able to use sed's -i option to modify files in place:

sed -i.bak 's/foo/bar/g' input-file

NOTE:

Not all versions of sed support -i.

Also, different versions of sed implement -i differently.

On some platforms you MUST specify a backup extension (on others you don't have to).

Solution 2

Since this is an incredibly simple file, sed may actually be overkill. It sounds like you want the file to have exactly one character: a '0' or a '1'.

It may make better sense in this case to just overwrite the file rather than to edit it, e.g.:

echo "1" > output 

or

echo "0" > output
Share:
13,263
Jason Kennaly
Author by

Jason Kennaly

I am an industrial controls engineer who spends a fair amount of time messing around with linux and webservers. I have over ten years experience trying to get PLCs, SCADA systems, instrumentation, controls, and upper management to work properly.

Updated on June 14, 2022

Comments

  • Jason Kennaly
    Jason Kennaly almost 2 years

    I have a file with 1 line of text, called output. I have write access to the file. I can change it from an editor with no problems.

    $ cat output
    1
    $ ls -l o*
    -rw-rw-r-- 1 jbk jbk 2 Jan 27 18:44 output
    

    What I want to do is replace the first (and only) line in this file with a new value, either a 1 or a 0. It seems to me that sed should be perfect for this:

    $ sed '1 c\ 0' output
     0
    $ cat output
    1
    

    But it never changes the file. I've tried it spread over 2 lines at the backslash, and with double quotes, but I cannot get it to put a 0 (or anything else) in the first line.