2

Much like this question, I've failed to put this together successfully on my own.

I want to truncate lines in my file so that no line is over 100 characters in length.

I can go to position 100 on each line and execute a d$ (or just a D), but what command will do this for every line in the file? Note: some lines are less than 100 characters.

Davo
  • 176
  • 3
  • 12

1 Answers1

7

Using a substitution

:%s/.\{100}\zs.*//

Find 100 characters, .\{100} then start the match, \zs, and select the rest of the line, .*. Replace the match with nothing.

For more help see:

:h :s
:h /\.
:h /\{
:h \zs
:h /\*

Using filter

:%!cut -c 1-100

Use filter, :!, with a range of the entire file, %. This will take the entire buffer and pass the text as stdin to cut and replace the buffer text with the stdout of our command. Use -c 1-100 to get the first 100 characters.

For more help see:

:!
:range

Using :normal

:%norm! v99lyVp

For every line, %, run command, {cmd} via :normal! {cmd}. Select and yank the first 100 characters via v99ly. Then replace the entire line, V with the just yanked 100 characters, p.

In theory, it would be nice to use 101|D, however 101| will just move to the end of the line for too short of lines. This will result short lines losing their trailing character. | also jumps by screen columns so could be messed up by indention.

For more help see:

:h :norm
:h :range
:h v_p
Peter Rincker
  • 15,854
  • 1
  • 36
  • 45