4

Possible Duplicate:
How do I use sudo to redirect output to a location I don’t have permission to write to?

Let's say I want to change a file "foo" that lives in /home, applying some regular expression to it (via sed), and put the result in a file called /home/foo2.

I don't have read/write access neither to /home or to foo, so then I use sudo. However, I still get a permission denied

sudo sed "s/bar/baz/" <foo >foo2
bash: foo2: Permission denied

Any ideas? Thanks

Community
  • 1
  • 1
knocte
  • 16,941
  • 11
  • 79
  • 125
  • 1
    You run into the problem because the shell does the I/O redirection before launching `sudo`, so it does the redirection with your own privileges, which you know aren't enough. Therefore, to get it to work, you have to get the program run by `sudo` to do the I/O redirection. Both answers that I see achieve that result. – Jonathan Leffler Oct 30 '12 at 16:46

2 Answers2

4

Use the in place option, -i. Your syntax would be:

sed -i [pattern] filename
Wug
  • 12,956
  • 4
  • 34
  • 54
  • -i is for reading the file, I'm getting a permission denied for writing it – knocte Oct 30 '12 at 15:18
  • 1
    oh oh! it turns out -i is for reading and writing in the same file, awesome thanks – knocte Oct 30 '12 at 15:21
  • (but then I had to do first sudo cp foo foo2) – knocte Oct 30 '12 at 15:22
  • I should have mentioned that I suspected you were running into issues reading and writing to/from the same file at the same time and that your issue was related to that instead of being a file permission issue. – Wug Oct 30 '12 at 15:30
  • 1
    well, thing is, in the command I wrote I had a typo: I wrote ">foo foo2 – knocte Oct 30 '12 at 15:39
1

Although sh might be a bad idea in general, this will give permission to create a new file foo2 for your shell:

sudo sh -c "sudo sed 's/bar/baz/' <foo >foo2"

P.P
  • 117,907
  • 20
  • 175
  • 238