Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed not replacing lines

Tags:

bash

replace

sed

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.

like image 547
Jason Kennaly Avatar asked Jan 28 '13 00:01

Jason Kennaly


2 Answers

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

like image 91
jahroy Avatar answered Oct 02 '22 12:10

jahroy


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
like image 24
Kevin Avatar answered Oct 02 '22 14:10

Kevin