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.

  • Do a macro if you know how to do it for a single line. Or smth like :%normal 100|d$ – Maxim Kim Nov 14 at 19:13
  • 1
    @MaximKim, :%norm 100|D will not work because 100| will just move to the end of the line on lines shorter than 100 chars. Meaning it will delete the last character for those lines. – Peter Rincker Nov 14 at 19:15
  • 1
    @PeterRincker this might work, with virtual edit set. – Christian Brabandt Nov 15 at 9:23
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
  • Excellent, thank you very, very much! – Davo Nov 14 at 19:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.