I want to use the command line to edit a text file but not overwrite it. I want to preserve the owner, group, and permissions of the file.
I have a file that holds a count of the number of times a piece of equipment is used. This file lets me know when the equipment needs to be serviced. There is zero concern about security, I need all users to be able to read and write this file.
If I use sed to edit the counts, it will overwrite the file, and the ownership and permissions of the file will be changed. I noticed that when I edit the file with vi, the ownership and permissions of the file are not changed.
I want to do the same thing from the command line. For example:
cat foo.txt
foo
ls -l foo.txt
-rw-rw-rw- 1 root root foo.txt
cat foo.txt | sed -e 's/foo/bar/' > foo.txt
ls -l foo.txt
-rw-r--r-- 1 joe admin foo.txt
This is a problem because both bill and joe use the script that updates the count file. When joe uses it, the permissions change that prevent bill from using it.
Since vi can edit text without changing owner and permissions, I assume it can be done, but I am having trouble figuring out how to do it.