How to correctly
Now, to do it right, you have to ensure that comments containing "slave" and "namenode" are ignored. I think this will work.
sed -n "/namenode/ s/^\([0-9][0-9]*.[0-9][0-9]*.[0-9][0-9]*.[0-9][0-9]*\) *s*[a-z]*namenode.*/\1/gp" /etc/hosts > masterssed -n "/slave/ s/^\([0-9][0-9]*.[0-9][0-9]*.[0-9][0-9]*.[0-9][0-9]*\) *slave.*/\1/gp" /etc/hosts > slaves
To get the whole line would be the same, but replace the /\1/ with /&/.
The answer provided by anubhava will also work, but could deliver wrong strings, specially if the IP address has an error such as 127.0.0.d1.