sed In-Place Editing In-place editing without specifying a backup file overrides read-only permissions

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

sed -i -e cmd file will modify file even if its permissions are set to read-only.

This command behaves similarly to

sed -e cmd file > tmp; mv -f tmp file

rather than

sed -e cmd file > tmp; cat tmp > file; rm tmp

The following example uses gnu sed:

$ echo 'Extremely important data' > input
$ chmod 400 input  # Protect that data by removing write access
$ echo 'data destroyed' > input
-bash: input: Permission denied
$ cat input  
Extremely important data (#phew! Data is intact)
$ sed -i s/important/destroyed/ input
$ cat input
Extremely destroyed data (#see, data changed)

This can be mitigated by creating a backup by specifying a SUFFIX with the i option:

$ sed -i.bak s/important/destroyed/ input
$ cat input
Extremely destroyed data
$ cat input.bak
Extremely important data


Got any sed Question?