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.
-
Isn't that what the -i option is for?
sed -i -e 's/foo/bar/' foo.txt
If you supply an argument to -i, it makes a backup for you.
Jon Angliss : I guess I should have tested that, never noticed it doesn't retain ownership information, but it does keep permissions.joshxdr : On solaris 8 the above command gives error "sed: illegal option -- i"Jon Angliss : Not sure on Solaris... Maybe switch to using perl? perl -e -i 's/foo/bar/' filename.txt... Or combine sed with a temp file, and the cat command to send the stuff back to the original file.From Jon Angliss
0 comments:
Post a Comment