Home > Mobile >  vim nested one-liner loop breaks command
vim nested one-liner loop breaks command

Time:12-10

I want to append a character multiple times for specific lines in a file so all of them would have x characters

Let's say I want all the lines between 20 and 80 to have the same number of characters(50) and the same character appended at the end:

for y in range(20, 80) | if strlen(getline(y)) !=50 | for i in range(50-strlen(getline(y))) | execute y .. 's/$/./' | endfor | endif | endfor

returns E727:Start past end and E1098: String, List or Blob required

if I use it with a specific line it works just fine if strlen(getline(N)) !=50 | for i in range(50-strlen(getline(N))) | execute N .. 's/$/./' | endfor | endif

Eg:

Input:

abcdef
defghijklm
foo

Output:

abcdef**********
defghijklm******
foo*************

CodePudding user response:

With GNU sed. First add 16 stars and then keep only the first 16 characters.

sed -E 's/$/&****************/; s/(.{16}).*/\1/' file

Output:

abcdef**********
defghijklm******
foo*************

CodePudding user response:

Your command is way too complicated for the little it does. The same outcome could be achieved with a much simpler:

:<from>,<to>s/$/\=repeat('*',50-strlen(getline('.')))
  • It is a quick :help :substitute with a range, a pattern, and a :help sub-replace-special expression.
  • <from>,<to> is our range, see :help :range.
  • $ is our zero-width pattern, the end of the line.
  • The very powerful \=<expr> allows us to use the string returned by <expr> as replacement.
  • :help repeat() repeats a given string a given number of times.
  • * is our string.
  • The number of repetitions is calculated with your own formula. When the line is longer than 50, the number of repetitions is negative, which means that there is no repetition and thus that no * is appended to the line.

Before:

a short line
some filler text foo
a line with 59 characters dgsfdsjgdfsjdshdlsjdfshjdsfdlhsjd
what

After:

a short line**************************************
some filler text foo******************************
a line with 59 characters dgsfdsjgdfsjdshdlsjdfshjdsfdlhsjd
what**********************************************
  • Related