Search code examples
bashsedscripting

Remove line containing hostname with sed


I have a host with the hostname babuntu10 and also hostname12, I want to remove only the hostname one from my fstab entry but the following sed command removes them both:

sed -i '/'"$HOSTNAME:"'/,$d' /etc/fstab

Input file:

babuntu10:/root/products/babuntu10 /root/products/babuntu10 nfs soft,timeo=1,retrans=1 0 0
babuntu12:/root/products/babuntu12 /root/products/babuntu12 nfs soft,timeo=1,retrans=1 0 0

I need to remove only the entry with the hostname.


Solution

  • sed '/x/,$d' is asking sed to delete all lines from the first one that matches x till the end of the file. Sounds like you just want to delete the matching line so that'd be sed '/x/d' instead.

    You should probably also add a start-of-string anchor ^ and use:

    sed -i '/^'"$HOSTNAME"':/d' /etc/fstab
    

    or, since the rest of your script is so brief and simple, you could just use double quotes around the whole thing:

    sed -i "/^$HOSTNAME:/d" /etc/fstab