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!
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.
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)".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With