tags:

views:

31

answers:

2

I have the following file

    more file
    machine1  network netmask  broadcast

how to add the "_NAME" after the first word in the line that have the "network netmask broadcast" words ?

remark sed also need to match only "network netmask broadcast" and then to add _NAME to the first word in the line

example: what I need to get after execute sed command

   machine1_NAME  network netmask  broadcast
+1  A: 

This should work, since we're not using the g modifier, it'll only match once per line

sed -e 's/^[^ ]*\>/&_NAME/'

It matches non-space characters up to the first word boundary, replacing it with itself and appends _NAME. As mentioned, without the g modifier it'll only match once per line, and if there are leading white space on the line, just remove the first ^-anchor.

Edit
you only wanted it to match on specific lines, so here goes:

sed -e '/network netmask broadcast$/s/^[^ ]*\>/&_NAME/'

The first part is a selector, which makes sure the substitution is only performed on lines where network netmask broadcast ends the line. To have it match any lines with those words, just remove the $-anchor, and add * (space-asterisk) to the spaces to make them flexible. But you probably already knew that.. :)

roe
+1  A: 
sed '/network.*netmask.*broadcast/s|^\([ \t]*\)\(.[^ \t]*\) |\1\2_NAME|' file
ghostdog74
@roe: Some versions of `sed` don't require the `-e`.
Dennis Williamson
@roe: don't edit unless unless you know what you are doing
ghostdog74
Sorry, I was just trying to be helpful, the -e is never wrong, but it may very well be incorrect to not use it, i.e. using it will pretty much always be safer. My bad.
roe
@Dennis; yes, but unfortunately not all. I'm pretty sure Solaris sed does require it, and there's no mention of GNU sed in there.
roe