Tuesday, November 30, 2010

Re: filter txt file based on start and ending marks

On 11/30/2010 04:01 PM, bboyjkang wrote:
>> :g/interesting/sil! ?start?,/end/s/^/XXX/
>> :v/^XXX/d
>> :%s/^XXX
>
> Is the "start" and "end" something you have to add yourself? Is it
> possible to do this: Let's say that once I find the pattern
> "interesting", I'd like to select the line that contains
> "interesting", or maybe include the line above and the line below that
> line that contains "interesting", for a total of 3 lines, or perhaps
> the entire paragraph that contains "interesting". Then, "start" is
> automatically put at the top of the paragraph/line(s), and "end" is
> put at the bottom of the paragraph/line(s). Now, I can do pattern
> matches or substitutions only on ranges between "start" and "end" that
> surround "interesting".

(Rearranged to trimmed inline-quoting rather than top-posting, as
is preferred on the mailing-list)

Yes, you can give other relative ranges. Note that it breaks down as

:g/pattern/action_to_perform_on_matching_lines

where action happens to be

<range>s/foo/bar/

(prefixed with "sil!" as previously detailed) and where <range>
happens to be "search backwards for pattern A, through searching
forwards to pattern B". For the line above/below version, you
could just change the range from the complex searches to
".-1,.+1" or more tersely, "-,+" as searches are relative to the
current line (the line found by each :g hit) so the "." is
optional, and adding/subtracting lines defaults to 1 if omitted.

:help :range

That would make the command

:g/interesting/sil! .-1,.+1s/^/XXX
or
:g/interesting/sil! -,+s/^/XXX

To adjust the number of lines of context, just change the "-1" to
however many lines you want before, and the "+1" to however many
lines you want after.

Note that you might hit a fence-posting case if the last
"interesting" match, plus whatever forward-context you want (in
this case, one line; in the previous case, searching forward to a
pattern) puts you beyond the end-of-file. So you might want to
hand-verify the final "interesting" match in the file.

-tim

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments:

Post a Comment