Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substitute without creating intermediate file in sed?

Tags:

linux

unix

sed

I was doing some hands-on with the Unix sed command. I was trying out the substitution and append command, in a file. But the difficulty is, I have to create an intermediate file, and then do mv to rename it to the original file.

Is there any way to do it at one shot in the same file?

[root@dhcppc0 practice]# sed '1i\
 > Today is Sunday
 > ' file1 > file1

[root@dhcppc0 practice]# cat file1
[root@dhcppc0 practice]#

The file is deleted!

[root@dhcppc0 practice]# sed 's/director/painter/' file1 > file1
[root@dhcppc0 practice]# cat file1

The file is deleted!

like image 898
RajSanpui Avatar asked Jul 31 '11 12:07

RajSanpui


People also ask

Does sed support multiline replacement?

By default, when sed reads a line in the pattern space, it discards the terminating newline (\n) character. Nevertheless, we can handle multi-line strings by doing nested reads for every newline.

What is sed s /\ g?

The sed expression s/~/ /g replaces every tilde with a space character. It means, literally, "substitute everything that matches the regular expression ~ with a space, globally (on the whole input line)".


1 Answers

Try this -

sed -i '' 's/originaltext/replacementtext/g' filename | cat filename

-i '' is meant for providing a backup file. If you are confident your replacement won't cause an issue you can put '' to pass no backup file

/g is for replacing globally. If you have more than one originaltext in one line then with /g option will replace all else it will only replace the first.

like image 191
dawnofthedead Avatar answered Oct 04 '22 22:10

dawnofthedead