On Wednesday 25 October 2006 15:57, Romanowski, John (OFT) wrote:
>I want to find the first comment line that begins with a target string
>in column 1 (#target) and replace only that first target line with
>another string.
>There are multiple lines that begin with #target.
>
>I've struck out with sed (not that I know sed).
>
>Any quick hints on a sed or awk or ?? sequence that does that?
Using GNU sed:
sed '0,/^#target/s/^#target.*/#.../' file
This uses the "0,addr2" GNU extension to sed so that the substitute command
will only be executed on lines up to and including the first line that
matches /^#target/. Because the substitute command also contains the pattern
match, only one line in that range (the last one, which is the first one
containing #target) will be changed. Note that the standard sed "1,addr"
would change two lines if #target is on the first line, but using this GNU
extension fixes that.
Using awk:
awk '/^#target/ && s == 0 {print "#..."; s = 1; next} {print}' file
This is more direct, because awk provides variables so it is easier to
maintain some state. Basically it says if we find the #target line and we
haven't found it before, print out something else and remember that we did
that. Otherwise, print out the line unchanged.
I'd recommend going with the awk command, because it is more portable and
easier for others to understand.
- MacK.
-----
Edmund R. MacKenty
Software Architect
Rocket Software, Inc.
Newton, MA USA
----------------------------------------------------------------------
For LINUX-390 subscribe / signoff / archive access instructions,
send email to [EMAIL PROTECTED] with the message: INFO LINUX-390 or visit
http://www.marist.edu/htbin/wlvindex?LINUX-390