Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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.

share|improve this question
    
You should know that redirecting to a file like you're doing in your example truncates it before it's read for processing, so sed will see an empty file (and the original contents are lost). –  Dennis Williamson Jul 8 '10 at 1:26
    
You are correct. I have changed the syntax. On my machine, cat foo.txt | sed -e 's/foo/bar/' > foo works ok. –  joshxdr Jul 9 '10 at 14:37
add comment

1 Answer

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.

share|improve this answer
    
I guess I should have tested that, never noticed it doesn't retain ownership information, but it does keep permissions. –  Jon Angliss Jul 7 '10 at 23:05
    
On solaris 8 the above command gives error "sed: illegal option -- i" –  joshxdr Jul 9 '10 at 14:39
    
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. –  Jon Angliss Jul 9 '10 at 19:17
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.