vim change newline into space but not every nth-line - vim

I have a file.txt of 1000 lines and every first 10 lines need to be on one line.
The eleventh line starts on a new line and is added with lines 12-20.
How can I do this in Vim!

I'm not 100% sure I grok what you're after, but I'll give you a few hints and perhaps they'll help.
To join lines together you can use J (that's capital J or Shift-J). You can precede this with a number, such as 10, and join 10 lines together. For example, typing 10J will give you:
Now, what you really need is a macro. This sounds fancy but it's just a way or recording a set of commands. So for example you could take 10J and record it to a macro. Repeat that macro 10 times and then you do that to 100 lines.
I think that the solution to your problem would therefore be something like this:
qa10Jjjq99#a
This does this (see below for an explanation):
Explanation:
q starts recording a macro. Everything that you type afterwards, until you type q again will be recorded. The next character a records the macro to the character a. Thus, qa of qa10Jjjq99#arecords 10Jjj to a. Now, to use the macro that you have stored to a you use the # symbol followed by the letter of where you stored the macro (in this case a, because we typed qa). The 99 means repeat this 99 times, thus, 99#a means repeat what's stored in macro a 99 times.
All together qa10Jjjq99#a means: record a macro q and store it in a. Then, join 10 lines 10J and move down two lines jj before stopping the recording q. Then repeat the macro stored 99 times 99#a.

Related

Join groups of N lines

I have a text file generated from an old database that consists of one line per field, with no delimiter between records other than knowing how many fields there are. What I'd like to do is join the first N lines, and then the next N, and so on. Is there any way to do this within Vim? Is there were a way to select lines to apply a command to based on an arbitrary VimL expression (like line(".")%5==0) instead of just a regex?
There are multiple ways of solving this. First that comes to my mind is recording a macro, say in register w:
qw5Jjq
This essentially uses the J normal command to join 5 lines and moves one down. Then you can repeat the macro for 20 times with a simple 20#w or keep repeating afterwards with ##.
Another, maybe more "proper" way is using the :join ex command, which is the same as the J normal command, but can be abbreviated to :j and used in conjunction with the :g to operate in various lines. For example:
:g/./j5
This will match every line non-empty line and in each one of them, join the next 5 lines (inclusive). Then move to the next line and join more 5 and so on.

Using gvim, to copy few lines and paste them at the start of each line [duplicate]

I’d like to merge two blocks of lines in Vim, i.e., take lines k through l and append them to lines m through n. If you prefer a pseudocode explanation: [line[k+i] + line[m+i] for i in range(min(l-k, n-m)+1)].
For example,
abc
def
...
123
45
...
should become
abc123
def45
Is there a nice way to do this without copying and pasting manually line by line?
You can certainly do all this with a single copy/paste (using block-mode selection), but I'm guessing that's not what you want.
If you want to do this with just Ex commands
:5,8del | let l=split(#") | 1,4s/$/\=remove(l,0)/
will transform
work it
make it
do it
makes us
harder
better
faster
stronger
~
into
work it harder
make it better
do it faster
makes us stronger
~
UPDATE: An answer with this many upvotes deserves a more thorough explanation.
In Vim, you can use the pipe character (|) to chain multiple Ex commands, so the above is equivalent to
:5,8del
:let l=split(#")
:1,4s/$/\=remove(l,0)/
Many Ex commands accept a range of lines as a prefix argument - in the above case the 5,8 before the del and the 1,4 before the s/// specify which lines the commands operate on.
del deletes the given lines. It can take a register argument, but when one is not given, it dumps the lines to the unnamed register, #", just like deleting in normal mode does. let l=split(#") then splits the deleted lines into a list, using the default delimiter: whitespace. To work properly on input that had whitespace in the deleted lines, like:
more than
hour
our
never
ever
after
work is
over
~
we'd need to specify a different delimiter, to prevent "work is" from being split into two list elements: let l=split(#","\n").
Finally, in the substitution s/$/\=remove(l,0)/, we replace the end of each line ($) with the value of the expression remove(l,0). remove(l,0) alters the list l, deleting and returning its first element. This lets us replace the deleted lines in the order in which we read them. We could instead replace the deleted lines in reverse order by using remove(l,-1).
An elegant and concise Ex command solving the issue can be obtained by
combining the :global, :move, and :join commands. Assuming that
the first block of lines starts on the first line of the buffer, and
that the cursor is located on the line immediately preceding the first
line of the second block, the command is as follows.
:1,g/^/''+m.|-j!
For detailed explanation of this technique, see my answer to
an essentially the same question “How to achieve the “paste -d '␣'”
behavior out of the box in Vim?”.
To join blocks of line, you have to do the following steps:
Go to the third line: jj
Enter visual block mode: CTRL-v
Anchor the cursor to the end of the line (important for lines of differing length): $
Go to the end: CTRL-END
Cut the block: x
Go to the end of the first line: kk$
Paste the block here: p
The movement is not the best one (I'm not an expert), but it works like you wanted. Hope there will be a shorter version of it.
Here are the prerequisits so this technique works well:
All lines of the starting block (in the example in the question abc and def) have the same length XOR
the first line of the starting block is the longest, and you don't care about the additional spaces in between) XOR
The first line of the starting block is not the longest, and you additional spaces to the end.
Here's how I'd do it (with the cursor on the first line):
qama:5<CR>y$'a$p:5<CR>dd'ajq3#a
You need to know two things:
The line number on which the first line of the second group starts (5 in my case), and
the number of lines in each group (3 in my example).
Here's what's going on:
qa records everything up to the next q into a "buffer" in a.
ma creates a mark on the current line.
:5<CR> goes to the next group.
y$ yanks the rest of the line.
'a returns to the mark, set earlier.
$p pastes at the end of the line.
:5<CR> returns to the second group's first line.
dd deletes it.
'a returns to the mark.
jq goes down one line, and stops recording.
3#a repeats the action for each line (3 in my case)
As mentioned elsewhere, block selection is the way to go. But you can also use any variant of:
:!tail -n -6 % | paste -d '\0' % - | head -n 5
This method relies on the UNIX command line. The paste utility was created to handle this sort of line merging.
PASTE(1) BSD General Commands Manual PASTE(1)
NAME
paste -- merge corresponding or subsequent lines of files
SYNOPSIS
paste [-s] [-d list] file ...
DESCRIPTION
The paste utility concatenates the corresponding lines of the given input files, replacing all but the last file's newline characters with a single tab character,
and writes the resulting lines to standard output. If end-of-file is reached on an input file while other input files still contain data, the file is treated as if
it were an endless source of empty lines.
Sample data is the same as rampion's.
:1,4s/$/\=getline(line('.')+4)/ | 5,8d
I wouldn't think make it too complicated.
I would just set virtualedit on
(:set virtualedit=all)
Select block 123 and all below.
Put it after the first column:
abc 123
def 45
... ...
and remove the multiple space between to 1 space:
:%s/\s\{2,}/ /g
I would use complex repeats :)
Given this:
aaa
bbb
ccc
AAA
BBB
CCC
With the cursor on the first line, press the following:
qa}jdd''pkJxjq
and then press #a (and you may subsequently use ##) as many times as needed.
You should end up with:
aaaAAA
bbbBBB
cccCCC
(Plus a newline.)
Explaination:
qa starts recording a complex repeat in a
} jumps to the next empty line
jdd deletes the next line
'' goes back to the position before the last jump
p paste the deleted line under the current one
kJ append the current line to the end of the previous one
x delete the space that J adds between the combined lines; you can omit this if you want the space
j go to the next line
q end the complex repeat recording
After that you'd use #a to run the complex repeat stored in a, and then you can use ## to rerun the last ran complex repeat.
There can be many number of ways to accomplish this. I will merge two blocks of text using any of the following two methods.
suppose first block is at line 1 and 2nd block starts from line 10 with the cursor's initial position at line number 1.
(\n means pressing the enter key.)
1. abc
def
ghi
10. 123
456
789
with a macro using the commands: copy,paste and join.
qaqqa:+9y\npkJjq2#a10G3dd
with a macro using the commands move a line at nth line number and join.
qcqqc:10m .\nkJjq2#c

Indent n rows n times

I am trying to indent several rows several times in Vim and could not figure out if there is a "direct" way to tell Vim to do so. For example, how do I indent 5 rows 5 indentation levels? I could of course do 5>>.... or Ctrl-V, mark 5 rows and then do 5>. But I was looking for something more like 5>5>, but that indents 25 lines one level instead.
You could combine block selection with what you're already doing i.e.
V5j5>
Which would select 5 rows down and indent the selected block 5 steps.
:>>>>>5
is another way.
vip5>
could solve your problem, too, if applicable.
And another slightly less practical (but very precise) one:
:,5le20
where 20 is the exact number of spaces (or tabs and spaces if :set noexpandtab) you want.
one way of doing this - you can make a macro to do that for you.
for example, to save a macro under key a, type following :
qaV5j5>q
q stands for starting/stopping typing onto register.
then, if you type #a macro from register a will be executed and your 5 lines will be indented 5 times. every repeated usage of last macro can be executed by ##.
if that helped, please check http://vim.wikia.com/wiki/Macros
Try this : :1,5s/^/ /

Repeat last change multiple times without replacing original count

The documentation for . says:
Repeat last change, with count replaced with [count].
Is it possible to repeat one change without replacing count and without resorting to macros?
Alternately, is it possible to repeat a change multiple times without the number being interpreted as the count value to the command?
Context:
I was working on this VimGolf challenge where the objective is to reverse the alphabet:
abcdefghijklmnopqrstuvwxyz becomes zyxwvutsrqponmlkjihgfedcba
My approach was to jump to z and use "Ax to append each letter to then of register a, and then paste register a, which would contain the reversed string. To repeat "Ax, recording a macro and using 25#q works, pressing . 26 times works, but 26. and 26"Ax do not work because 26 is applied to the count of x, which makes the command attempt to delete 26 characters to the right of the cursor.
what you need here is macro, not [count]. because . repeat the last cmd. and if you give it count, as you have seen, the count would be applied on the last cmd, so it would be 26x, not pressing x 26 times. usually there is no difference, but if your cursor is at the end of the line, 26x does the same as x.
What you need is a macro, if you don't want to qx...q, there are some tricks you may want to know: (without thinking about the count of keystrokes too much)
trick1
use the = register:
26#='"Ax'<cr>
this does what you want.
trick2
use the . register.
Assume at the start point, your cursor is on the line1 col1 so, press: A"Ax<esc>U26#.
the first A jump to EOL and entering INSERT, big U undo the inserted text of current line, and save into '.' (dot) register.
Now you can "replay" the reg 26 times.
regarding this challenge, the most straightforward solution (might not be the shortest) would be: set revins option, in short: se ri.
hope it helps.

How to merge two multi-line blocks of text in Vim?

I’d like to merge two blocks of lines in Vim, i.e., take lines k through l and append them to lines m through n. If you prefer a pseudocode explanation: [line[k+i] + line[m+i] for i in range(min(l-k, n-m)+1)].
For example,
abc
def
...
123
45
...
should become
abc123
def45
Is there a nice way to do this without copying and pasting manually line by line?
You can certainly do all this with a single copy/paste (using block-mode selection), but I'm guessing that's not what you want.
If you want to do this with just Ex commands
:5,8del | let l=split(#") | 1,4s/$/\=remove(l,0)/
will transform
work it
make it
do it
makes us
harder
better
faster
stronger
~
into
work it harder
make it better
do it faster
makes us stronger
~
UPDATE: An answer with this many upvotes deserves a more thorough explanation.
In Vim, you can use the pipe character (|) to chain multiple Ex commands, so the above is equivalent to
:5,8del
:let l=split(#")
:1,4s/$/\=remove(l,0)/
Many Ex commands accept a range of lines as a prefix argument - in the above case the 5,8 before the del and the 1,4 before the s/// specify which lines the commands operate on.
del deletes the given lines. It can take a register argument, but when one is not given, it dumps the lines to the unnamed register, #", just like deleting in normal mode does. let l=split(#") then splits the deleted lines into a list, using the default delimiter: whitespace. To work properly on input that had whitespace in the deleted lines, like:
more than
hour
our
never
ever
after
work is
over
~
we'd need to specify a different delimiter, to prevent "work is" from being split into two list elements: let l=split(#","\n").
Finally, in the substitution s/$/\=remove(l,0)/, we replace the end of each line ($) with the value of the expression remove(l,0). remove(l,0) alters the list l, deleting and returning its first element. This lets us replace the deleted lines in the order in which we read them. We could instead replace the deleted lines in reverse order by using remove(l,-1).
An elegant and concise Ex command solving the issue can be obtained by
combining the :global, :move, and :join commands. Assuming that
the first block of lines starts on the first line of the buffer, and
that the cursor is located on the line immediately preceding the first
line of the second block, the command is as follows.
:1,g/^/''+m.|-j!
For detailed explanation of this technique, see my answer to
an essentially the same question “How to achieve the “paste -d '␣'”
behavior out of the box in Vim?”.
To join blocks of line, you have to do the following steps:
Go to the third line: jj
Enter visual block mode: CTRL-v
Anchor the cursor to the end of the line (important for lines of differing length): $
Go to the end: CTRL-END
Cut the block: x
Go to the end of the first line: kk$
Paste the block here: p
The movement is not the best one (I'm not an expert), but it works like you wanted. Hope there will be a shorter version of it.
Here are the prerequisits so this technique works well:
All lines of the starting block (in the example in the question abc and def) have the same length XOR
the first line of the starting block is the longest, and you don't care about the additional spaces in between) XOR
The first line of the starting block is not the longest, and you additional spaces to the end.
Here's how I'd do it (with the cursor on the first line):
qama:5<CR>y$'a$p:5<CR>dd'ajq3#a
You need to know two things:
The line number on which the first line of the second group starts (5 in my case), and
the number of lines in each group (3 in my example).
Here's what's going on:
qa records everything up to the next q into a "buffer" in a.
ma creates a mark on the current line.
:5<CR> goes to the next group.
y$ yanks the rest of the line.
'a returns to the mark, set earlier.
$p pastes at the end of the line.
:5<CR> returns to the second group's first line.
dd deletes it.
'a returns to the mark.
jq goes down one line, and stops recording.
3#a repeats the action for each line (3 in my case)
As mentioned elsewhere, block selection is the way to go. But you can also use any variant of:
:!tail -n -6 % | paste -d '\0' % - | head -n 5
This method relies on the UNIX command line. The paste utility was created to handle this sort of line merging.
PASTE(1) BSD General Commands Manual PASTE(1)
NAME
paste -- merge corresponding or subsequent lines of files
SYNOPSIS
paste [-s] [-d list] file ...
DESCRIPTION
The paste utility concatenates the corresponding lines of the given input files, replacing all but the last file's newline characters with a single tab character,
and writes the resulting lines to standard output. If end-of-file is reached on an input file while other input files still contain data, the file is treated as if
it were an endless source of empty lines.
Sample data is the same as rampion's.
:1,4s/$/\=getline(line('.')+4)/ | 5,8d
I wouldn't think make it too complicated.
I would just set virtualedit on
(:set virtualedit=all)
Select block 123 and all below.
Put it after the first column:
abc 123
def 45
... ...
and remove the multiple space between to 1 space:
:%s/\s\{2,}/ /g
I would use complex repeats :)
Given this:
aaa
bbb
ccc
AAA
BBB
CCC
With the cursor on the first line, press the following:
qa}jdd''pkJxjq
and then press #a (and you may subsequently use ##) as many times as needed.
You should end up with:
aaaAAA
bbbBBB
cccCCC
(Plus a newline.)
Explaination:
qa starts recording a complex repeat in a
} jumps to the next empty line
jdd deletes the next line
'' goes back to the position before the last jump
p paste the deleted line under the current one
kJ append the current line to the end of the previous one
x delete the space that J adds between the combined lines; you can omit this if you want the space
j go to the next line
q end the complex repeat recording
After that you'd use #a to run the complex repeat stored in a, and then you can use ## to rerun the last ran complex repeat.
There can be many number of ways to accomplish this. I will merge two blocks of text using any of the following two methods.
suppose first block is at line 1 and 2nd block starts from line 10 with the cursor's initial position at line number 1.
(\n means pressing the enter key.)
1. abc
def
ghi
10. 123
456
789
with a macro using the commands: copy,paste and join.
qaqqa:+9y\npkJjq2#a10G3dd
with a macro using the commands move a line at nth line number and join.
qcqqc:10m .\nkJjq2#c

Resources