Using Sed to remove part of line with regex

Greetings everyone. Right now I am working on a script to be used during automated deployment of servers. What I have to do is remove localhost.localdomain and localhost6.localdomain6 from the /etc/hosts file. Simple, right? Except most of the examples I've found using sed want to delete the entire line.
Here's the example contents of the file:

# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1               localhost.localdomain localhost
::1             localhost6.localdomain6 localhost6
172.30.0.133  loghost

Here's the regex I was planning to use:

 /\bl.*(n|n6)\b/g

I tested it and it looks like its working. Now I just have to figure out how to use it in sed. The file needs to be left in place, so I know it'll be starting something along these lines...
sed -i (delete) /\bl.*(n|n6)\b/g /etc/hosts

Any help would be very much appreciated; I'm still getting used to using sed and 90% of the examples still look completely cryptic to me.

My ultimate goal is to have the /etc/hosts file look like this:

# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1               localhost
::1             localhost6
172.30.0.133  loghost

Are you sure you want to use that regex? It will match any hostname starting with "l" and ending with "n", so if your hosts file contains hostnames like "lion" etc, it will get deleted too. Try this instead:

 perl -i -pe 's/localhost6?\.localdomain6?//' /etc/hosts
1 Like

Awesome! That worked like gangbusters. I wasn't super worried about other hostnames since all hosts come out of the automation system with the same hostname, but this works just as well. Thanks!

you can try this :wink:

# sed 's/localhost6*.localdomain6*//'
1 Like

Oh cool, I didn't know you could substitute with nothing :slight_smile: Thank you!