Re: lines matching N and N+1
Joel Hammer <[email protected]>
| Newsgroups | gmane.editors.sed.user |
|---|---|
| Message-ID | <1359605882.3771.113.camel@hammer11> |
Brute force is always my way.
sed "
:loop1
N
/[^\n]*foo */{
/\n[a-z ]*bar /{
s/\(foo\)\([ \n]\)/FOO\2/
s/\(\n[a-z ]*\)\(bar \)/\1BAR /
P
s/.*\n//
bloop1
}
/\n[a-z ]*bar$/{
s/\(foo\)\([ \n]\)/FOO\2/
s/\(\n[a-z ]*\)\(bar\)$/\1BAR/
P
s/.*\n//
bloop1
}
}
P
s/.*\n//
bloop1
" yourfile
In English.
Read in one line.
With N, append 2nd line.
Search for foo in first line
If no foo, P the first line, erase it, then N the next line.
If foo in first line, is there bar[blank] in 2nd line? If so, capitalize
foo and bar, P the first line, erase the first line, then N the next
line.
If no bar[blank], is there a bar$ in 2nd line? If so, capitalize, etc.
If no bar is found, P the first line, erase the first line, N in the
next line.
(Note: Matching bar in the 2nd line was tougher than foo in the first
line)
This seems to work for all combinations of foo and bar, whether they
occur on the same line or in the last line of the file, etc. YMMV.
Joel
On Mon, 2013-01-28 at 20:18 +0000, Daniel wrote:
>
> This came up in a recent cross-Atlantic conversation. :)
>
> The problem: How to apply a change when a *combination*
> of lines occurs, eg when the word "foo" appears in line
> N and the word "bar" appears in line N+1. How then to
> apply the change in line N (or line N+1)? For example,
> change word "foo" to "FOO" and word "bar" to "BAR".
>
> Here's a test file I dreamed up:
>
> food foot foo
> bare bark bar
> bar bark bare
> bark bar bare
> foot foo food
> bark bar bare
> foot foo food
> foo foot food
> bar bark bare
> foot foo food
>
> Here's the desired output:
>
> food foot FOO
> bare bark BAR
> bar bark bare
> bark bar bare
> foot FOO food
> bark BAR bare
> foot foo food
> FOO foot food
> BAR bark bare
> foot foo food
>
> I tried doing this in bash and couldn't make it
> work. I do have a possible sed solution.
>
> Thought I'd post this, see if anyone would like
> to take a look, either sed or bash (or whatever!).
>
> Daniel
>
>
>
>
>