1 |
On Wednesday 26 September 2007, Donnie Berkholz wrote: |
2 |
> On 00:02 Wed 26 Sep , Stephen Bennett wrote: |
3 |
> > On Tue, 25 Sep 2007 11:10:34 +0200 |
4 |
> > |
5 |
> > Robert Buchholz <rbu@g.o> wrote: |
6 |
> > > I already wondered a while back: |
7 |
> > > sed only fails if the file does not exist, but not if there was no |
8 |
> > > replacement. Is there any way to force it to? |
9 |
> > |
10 |
> > Off the top of my head... |
11 |
> > |
12 |
> > sed -e '1{x;s/^/0/;x;ta;:a}' |
13 |
> > -e 's/$STRING/$REPLACEMENT/' |
14 |
> > -e 'Tb;x;s/^/1/;x;:b;${p;x;/^0/Q1;Q0};' |
15 |
> |
16 |
> I spent a few minutes trying to decipher that without luck. Could you |
17 |
> walk me through it? |
18 |
|
19 |
sed maintains two buffers - pattern and hold (which start out empty) and |
20 |
that's the trick here |
21 |
|
22 |
{ } - used to group commands together |
23 |
|
24 |
1 - only match first line (it's an address match) |
25 |
x - swap pattern space and hold space |
26 |
s/^/0/ - turn the (now) empty pattern space into "0" |
27 |
x - swap pattern space and hold space |
28 |
ta - branch to label a if previous expression matched something |
29 |
a: - the actual label "a" ... needed to reset branching conditions |
30 |
|
31 |
Tb - branch to label b if previous expression matched something |
32 |
x - swap pattern space and hold space |
33 |
s/^/1/ - insert "1" into the pattern space |
34 |
x - swap pattern space and hold space |
35 |
:b - the actual label "b' |
36 |
|
37 |
$ - only match the last line (it's an address match) |
38 |
p - print current pattern space |
39 |
x - swap pattern space and hold space |
40 |
/^0/Q1;Q0 - if the pattern space starts with a 0, exit with 1 ... otherwise |
41 |
continue on to the exit with 0 ... either way, quit without printing |
42 |
|
43 |
the optional argument to Q is a GNU extension which isnt documented in the |
44 |
manpage :( ... guess i'll send them a patch |
45 |
|
46 |
pretty sure the first expression can be dropped: |
47 |
sed -e 's/$STRING/$REPLACEMENT/' \ |
48 |
-e 'tb;x;s/^/1/;x;:b;${p;x;/^$/Q1;Q0};' |
49 |
|
50 |
and the printing makes it a little reliant on how sed is used ... i think |
51 |
something like this should work with -n: |
52 |
-e 'Tb;x;s/^/1/;x;:b;${x;/^$/{x;q1};x;q0}' |
53 |
-mike |