Domanda

I'm trying to automate some simple modifications to a set of files with a script using vim ex mode. What I want to do is search for a pattern, delete it from its current location (just the pattern, not the whole line), and paste it at the end of the document.

There are some useful suggestions at the following URL, but I feel like there ought to be a way of doing this without defining a special function. http://vim.wikia.com/wiki/Copy_the_search_results_into_clipboard

Recommendations?

È stato utile?

Soluzione

Ex commands typically work on entire lines. However we can use the command :s to "capture" all the matches into a register and then paste them at the end of the document.

:let @a=""
:%s//\=matchstr(setreg('A',submatch(0),'l'),'')/g
:$put a

Explanation:

  • Blank out the a register via let @a=""
  • Substitute the last used search pattern: %s//....
  • Use an expression, \=, as the substitution
  • submatch(0) represents the matched pattern
  • Append to the a register linewise the matching pattern via: setreg('A',submatch(0),'l')
  • Because setreg() returns a zero we use matchstr() to basically convert it to an empty string
  • use the /g flag to match multiple times per line
  • Paste the matches were collected in the a register to the end of the document via $pu a

For more help see:

:h :let
:h :s
:h range
:h :s\=
:h submatch(
:h setreg(
:h matchstr(
:h :pu
:h registers
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top