Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text substitution (reading from file and saving to the same file) on linux with sed

Tags:

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: http://idolinux.blogspot.com/2008/08/sed-in-place-edit.html here's my updated code:

sed -i -e 's/find/replace/g' teste  
like image 638
Roger Avatar asked Jun 26 '11 13:06

Roger


People also ask

How do I save a file after sed command?

Your sed command only sends its result to the standard output. You would have to redirect it in a subsequent command (NOT in the same command, like sed 'sedcommand' file > file , as this would erase the file before processing it).

Which sed command is used to modify all text matches in a line of text?

'g' option is used in `sed` command to replace all occurrences of matching pattern. Create a text file named python.

Does sed modify files?

There is a huge pool of commands available for Ubuntu and sed command utility is one of them; the sed command can be used to perform fundamental operations on text files like editing, deleting text inside a file.


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

like image 71
geekosaur Avatar answered Sep 24 '22 20:09

geekosaur


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

like image 30
Antti Avatar answered Sep 24 '22 20:09

Antti