3

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.

2
  • 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). Jul 8, 2010 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, 2010 at 14:37

1 Answer 1

1

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.

3
  • I guess I should have tested that, never noticed it doesn't retain ownership information, but it does keep permissions. Jul 7, 2010 at 23:05
  • On solaris 8 the above command gives error "sed: illegal option -- i"
    – joshxdr
    Jul 9, 2010 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. Jul 9, 2010 at 19:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .