sed/awk : how to delete lines based on IP pattern ?

Hi,

I would like to delete lines in /etc/hosts on few workstations, basically I want to delete all the lines for a list of machines like this :

for HOST in $(cat stations.lst |uniq)
do
# echo -n "$HOST"
  if ping -c 1 $HOST  > /dev/null 2>&1
  then
      HOSTNAME_val=`rsh  $HOST "sed whatever /etc/hosts"`
      val1=`echo $HOSTNAME_val` 
    echo $val1
      else 
       echo "$HOST ; not responding"
  fi
done

"whatever" means "all the lines that contain 152.15.x.y, 152.9.x.y, 152.19.x.y and 44.33.x.y"

I need help for the sed part.
I was thinking of something like

sed '/152.15./d' /etc/hosts

but I don't know how to put my four patterns on the same line (or even if is it possible).

Thanks for your help

Here is one way:

sed '/152.15.x.y/d;/152.9.x.y/d;/152.19.x.y/d;/44.33.x.y/d' /etc/hosts
1 Like

Once you know the sed command works as expected, you can use the -i option to replace the file you just edited.

Also, Shell_Life's example makes one big mistake: using unescaped periods (.) to represent the dot in an IP address. That can lead to big problems. Make sure you escape all periods like this:

sed -i '/152\.15\.3\.4/d;'

Another "gotcha" with the above example is that it will also nail ip addresses like "152.15.3.42". Since that's probably not what you want, do this:

sed -i '/^152\.15\.3\.4[\t ]/d;'

This makes sure that the 4 precedes a tab or space.

1 Like

Thanks to you two

I will try this tomorrow and I'll let you know if I've succeded doing what I want :slight_smile:

---------- Post updated 18-10-11 at 10:46 AM ---------- Previous update was 17-10-11 at 06:56 PM ----------

Hello again

Here is what I've done :

for HOST in $(cat stations.lst | uniq)
do
  # echo -n "$HOST"
  if ping -c 1 $HOST > /dev/null 2>&1
  then
    HOSTNAME_val=`rsh  $HOST "cp /etc/hosts /etc/hosts.dirty ; sed '/152\.15\./d;/152\.9\./d;/152\.19\./d;/44\.33\./d' /etc/hosts > /etc/hosts.clean ; mv /etc/hosts.clean /etc/hosts"`
    val1=`echo $HOSTNAME_val` 
    echo $val1
  else 
    echo "$HOST ; not responding"
  fi
done

The reason why I did not use the -i option is because many of the workstations are HP-UX and sed does not recognize de -i option on this system...

It's working great, thanks !