Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove newlines from a register in vim?

I have a long list of different names of universities. I'm trying to build a synonym table by collating lines with certain unique keywords; that is, in the file, I'll identify that Harvard is the keyword here:

Harvard Business School|
Harvard College|
Harvard School of Divinity|

and paste them into another file as

Harvard Business School|Harvard College|Harvard School of Divinity|

I have been doing this by searching for the word under the cursor, yanking lines with that word into register, pasting the register into the other file, and using the join command "J" to join the lines together:

[ clear register 'a' ]    
0"ay0
[ move cursor to 'Harvard" and yank lines with keyword into register a ]
:g/\<<CTRL-R><CTRL-W>\>/y A
[ move to other screen and paste ]
"ap
[ join lines ]
JJJJJ

This works just fine, but I'd like it to be streamlined. Specifically, I would like to know how to remove newlines from a register so that I don't have to use JJJJ to manually join the lines in the last step. I'd like to search for all lines containing the word under the cursor, copy them into the 'a' register, remove newlines from the 'a' register, then paste the contents of the 'a' register.

Any ideas?

EDIT: I know:

  • how to search and replace globally, e.g. %s/\n//g
  • how to search and replace 'foo' in a buffer from a word to the contents of a register, e.g. :%s/foo/a/g
  • how to search for the contents of a register and replace with 'foo' in a buffer, e.g. :%s/a/bar/g

What I need to know:

  • how to search and replace 'foo' with 'bar' from register 'a' to register 'b'
  • how to search and replace 'foo' with 'bar' from register 'a' to register 'a'
like image 584
Myer Avatar asked Feb 24 '23 00:02

Myer


2 Answers

To do it directly with text in register a you could use this command:

:let @a=substitute(strtrans(@a),'\^@',' ','g')

Then you should get results you want when you paste register a back in.

like image 134
Herbert Sitz Avatar answered Feb 27 '23 10:02

Herbert Sitz


You don't need to remove newlines from register or press more then one J: with the following mapping it will be "apgVJ:

nnoremap <expr> gV    "`[".getregtype(v:register)[0]."`]"

This mapping makes you able to select pasted text just after it was pasted. J on selected region joins all lines in region (unless region has only one line: here J acts like J without a selection, joining current line with next). gV tip can also be used to do substitution: "apgV:s/{pattern}/{replacement}<CR> is more convenient then using "ap:let @a=substitute(@a, '{pattern}', '{replacement}', '{flags}') unless you define some smart mapping.

Another tip is that register a can be cleared using qaq normal mode sequence: qa starts recording a new macro and q immediately stops it leaving empty string in a register where macro is recorded to.

like image 45
ZyX Avatar answered Feb 27 '23 09:02

ZyX