1

My first time on Stack:

I'm doing a pattern match as follows. $VAR1 in this case is "/usr/lib/sendmail". The variable is read in from a separate file using a while loop.

cat /etc/rc.tcpip |grep -w "^start[[:blank:]]${VAR1}"

I want to "comment the line" (#) at the beginning of the match. I'm sure it's sed but I just can't seem to figure out how to make it work.

So existing line:

start /usr/lib/sendmail "$src_running" "-bd -q${qpi}"

desired result:

# start /usr/lib/sendmail "$src_running" "-bd -q${qpi}"
meuh
  • 11,500
  • 2
  • 29
  • 45
  • 1
    You have a UUOC in there: http://www.smallo.ruhr.de/award.html. `cat $FILE | grep $PATTERN` is unnecessary. You can simply do `grep $PATTERN $FILE` or `grep $PATTERN < $FILE`. – Tripp Kinetics Aug 07 '15 at 15:43
  • BashFAQ #21, http://mywiki.wooledge.org/BashFAQ/021, is well worth reading. (Yes, it _does_ explicitly apply to ksh). – Charles Duffy Aug 07 '15 at 15:58
  • The line beginning *after* the match, or the one beginning *with* the match? Your examples clearly seem to show the latter. – Charles Duffy Aug 07 '15 at 15:58

1 Answers1

1

Try

sed '\|^start[[:blank:]]'"$VAR1"'|s/^/# /' /etc/rc.tcpip

You need \| as your var has / in it. If you sed accepts -i you can put the result in the same file.

Normally the sed command would take the form:

/pattern1/s/pattern2/replacement/

where pattern1 selects a line to apply the substitute (s) to, pattern2 is what to match, and replacement is what to replace the match by. In your case pattern1 contains the slash char / so to use it in pattern1 it would need to be escaped with \. However the slashes are inside $VAR1, so we would need to edit $VAR1 to replace every / with \/.

Instead it is simpler to use an alternative delimiter instead of /, just for /pattern1/. The syntax for this is a little bizarre and non-symmetric:

\|pattern1|s/pattern2/replacement/

The \ at the start of the line says the next char is an alternative delimiter. I chose |, but another char not in pattern1 could do just as well, eg

\;pattern1;s/pattern2/replacement/
meuh
  • 11,500
  • 2
  • 29
  • 45
  • Thank you... This does work. However, putting code in my script I don't fully understand will "bite" me eventually. So, why does the "\" escape occur in the beginning before the "|" and not directly in front of the variable. I understand what it's needed for but don't understand the placement. Sorry for the extra question, but I truly need understand how it function. Thank you!! – Pete N Meyburg Aug 10 '15 at 16:51
  • @PeteNMeyburg I added an explanation – meuh Aug 10 '15 at 17:05