Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to delete specific line from hosts file in my home dir:

~$ echo "193.10.1.1 localhost" >> hosts
~$ echo "127.0.0.1 localhost" >> hosts
~$ cat hosts
193.10.1.1 localhost
127.0.0.1 localhost
~$ sed '/127.0.0.1/d' hosts > hosts
~$ cat hosts

But file is emtpy. How do I delete mactching line and then print result back in file?

share|improve this question
up vote 4 down vote accepted

The file is truncated when you redirect output using >, before the sed command actually runs.

BSD sed

Use sed -i .bak '/^127\.0\.0\.1[[:space:]]/d' hosts instead to edit a file inline, saving a backup with the bak extension, or sed -i '' [...] to skip backup creation.

GNU sed

Use sed -ibak '/^127\.0\.0\.1[[:space:]]/d' hosts instead to edit a file inline, saving a backup with the bak extension, or sed -i [...] to skip backup creation.


You can also do this manually, e.g. the following:

sed '/^127\.0\.0\.1[[:space:]]/d' hosts > hosts.new
cat hosts.new > hosts
rm hosts.new

While this is one more line that mv hosts.new hosts, it'll retain the file metadata of hosts.

share|improve this answer
    
@Mighter You might have a different sed. Skip the argument to -i, i.e. sed -i '/127.0.0.1/d' hosts – Daniel Beck Aug 27 '12 at 8:48
    
Yes, without bak it does the trick. Thanks! – Igor Filippov Aug 27 '12 at 8:50

You must log in to answer this question.

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