How to replace without creating an intermediate file in sed?

I practiced using the Unix sed command. I tried to execute the substitution and append command in the file. But the problem is that I have to create an intermediate file and then mv rename it to the source file.

Is there a way to do this with one shot in a single file?

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

File deleted!

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

File deleted!

+7
source share
3 answers

GNU sed knows the -i option, which does in-place data editing.

When performing the operation file1 > file1 , what actually happens is that the file is opened and truncated by the shell before , the program (which receives this name as an argument) comes with it, reading something from it.

Update

The sed man page specifies the following in the -i option (thanks to Delan for mentioning):

  -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if extension supplied) 
+11
source

Try it -

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

-i '' is intended to provide a backup file. If you are sure that your replacement will not cause a problem, you can put "do not transfer the backup file"

/ g - to replace globally. If you have more than one source text in one line, then the / g option will replace all the others, this will replace only the first.

+11
source

sed -i.bak 's / director / painter /' file1

  -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if extension supplied) 
+1
source

All Articles