Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

1 Answer 1

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! –  Mighter Aug 27 '12 at 8:50

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.