I want to read the file "teste", make some "find&replace" and overwrite "teste" with the results. The closer i got till now is:

$cat teste I have to find something This is hard to find... Find it wright now! $sed -n 's/find/replace/w teste1' teste $cat teste1 I have to replace something This is hard to replace... 

If I try to save to the same file like this:

$sed -n 's/find/replace/w teste' teste 

or:

$sed -n 's/find/replace/' teste > teste 

The result will be a blank file...

I know I am missing something very stupid but any help will be welcome.


UPDATE: Based on the tips given by the folks and this link: here's my updated code:

sed -i -e 's/find/replace/g' teste 
0

7 Answers

On Linux, sed -i is the way to go. sed isn't actually designed for in-place editing, though; historically, it's a filter, a program which edits a stream of data in a pipeline, and for this usage you would need to write to a temporary file and then rename it.

The reason you get an empty file is that the shell opens (and truncates) the file before running the command.

4

You want: sed -i 's/foo/bar/g' file

1

You want to use "sed -i". This updates in place.

In-place editing with perl

perl -pi -w -e 's/foo/bar/g;' file.txt 

or

perl -pi -w -e 's/foo/bar/g;' files* 

for many files

The ed solution is:

ed teste <<END 1,$s/find/replace/g w q END 

Or without the heredoc

printf "%s\n" '1,$s/find/replace/g' w q | ed teste 
0

Actually, if you use -i flag, sed will copy the original line you edit.

So this might be a better way:

sed -i -e 's/old/new/g' -e '/new/d' file 
0

There is a useful sponge command.

sponge soaks up all its input before opening the output file.

$cat test.txt | sed 's/find/replace/w' | sponge test.txt 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy