Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vi VIM How to append line to itself?

I want to append the entire content of the line (excluding the ending newline) to the line itself. I saw this solution :%s/$/\*/g here: How can I add a string to the end of each line in Vim?

But it is appending the character * to the lines. I tried both :%s/$/*/g and :%s/$/\*/g but the same result.

I am using VIM - Vi IMproved version 7.3.46

PS: it seems, as a new user i am not allowed to post this question as a comment there. thanks.

like image 591
Tem Pora Avatar asked Dec 02 '22 20:12

Tem Pora


2 Answers

Once again, command mode is vastly underrated:

:t.|-j

DONE

Update I saw in another comment that you want to do this for a range. This is easy too. See below

This is basically the Ex equivalent of yyPJx except

  1. It won't clobber any registers
  2. Won't shift the "0-"9 registers
  3. Won't affect the current search and/or search history (like in the :%s based answer)
  4. Can be immediately repeated by doing @: - no macros, no mappings :)
  5. will result in atomic undo (whereas the yyPJx approach would result in 3 separate undo steps)

Explanation:

  • :t is synonym for :copy
  • :j is short for :join
  • :-j is short for :-1join, meaning: join the previous line with it's successor

Note: If you wanted to preserve leading whitespace (like yyPgJx instead of yyPgJx) use:

:t.|-j!

Update for repeats, with a visual selection type

:'<,'>g/^/t.|-j

Which repeats it for every line in the visual selection. (Of course, :'<,'> is automatically inserted in visual mode). Another benefit of this approach is that you can easily specify a filter for which lines to duplicate:

:g/foo/t.|-j

Will 'duplicate' all lines containing 'foo' in the current buffer (see windo, bufdo, argdo to scale this to a plethora of buffers without breaking a sweat).

like image 78
sehe Avatar answered Dec 09 '22 15:12

sehe


You can use this substitution:

:s/^.*$/&&
  • ^.*$ means "whatever (.*) is between the beginning (^) and end ($) of the line".
  • & represents the matched text so we are substituting the whole line with itself followed by itself again.

edit

Ingo's comment is spot-on: :s/.*/&& does the same with less typing.

like image 30
romainl Avatar answered Dec 09 '22 14:12

romainl