Monday, September 20, 2010

Re: Search 2 string and copy string inbetween in a new file

On 09/20/10 13:11, Christian Brabandt wrote:
> On Mo, 20 Sep 2010, HermannHeilner wrote:
>> Search a specific pattern A, then search a specific pattern B, then mark the
>> letters between these two patterns and copy these into a new file.
>
> For example, you search from the current cursor position the beginning
> of foobar and want to write until the next baz. You can simply do this:
> /^foobar/+,/^baz/-w foobar.txt
> This copies the text between the lines to the file foobar.txt If you
> want to include the start and end patterns, leave the + and - signs out.

Christian gives a workable solution for a certain line-format,
assuming your search-items are on their own lines, and the
contents between them are also on their own line(s).

It gets a little trickier when you have them inline:

aaaacgtaggggggatgca
^^^^^^^^

if you want to extract the information between "acgt" and "tgca"
(in the above example "agggggga"), you'd have to pull the text in
visual mode, and use search-offsets

:nnoremap <f4> /acgt/e+1<cr>v/tgca/s-1<cr>y:new<cr>P

would map <f4> to

/acgt/e+1 " search for 'acgt' and position the cursor
" at the end+1 of the match
<cr> " execute the search
v " go into character-wise visual mode
/tgca/s-1 " search for 'tgca' and position the cursor
" at start-1 (the character before the match)
<cr> " execute the search
y " yank the resulting text
:new<cr> " create a new unnamed buffer
P " paste the yanked text in this new buffer


You can then save this new buffer as you would any other:

:w /path/to/wherever/extract.txt

It gets a little trickier if you want to have it mapped *and*
provide the patterns dynamically, but it can be done:

:let b:start = "acgt"
:let b:end = "tgca"
:nnoremap <f4>
/<c-r>=b:start<cr>/e+1<cr>v/<c-r>=b:end<cr>/s-1<cr>y:new<cr>P

should come fairly close. That way, you could tweak the values
for b:start and b:end and <f4> should Do The Right Thing(tm).

To read up on some of these bits:

:help /
:help {offset}
:help c_CTRL-R_=

Hope this helps,

-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: