1

How can I remove all but the first n characters of a every line in the file buffer?

What I tried

Mark region
C-x r k #but this is cumbersome when the length of lines are very varied, and there are over 100 lines
3
  • Try rectangle editing.
    – Dan
    Commented Feb 8, 2018 at 18:52
  • rectangle editing misses segments when some lines in the middle are lengthy Commented Feb 8, 2018 at 20:06
  • Well... rectangle editing does what you tell it to do -- if it 'misses' segments it's because you didn't make your rectangle the appropriate width. (I do know what you mean though -- it might not be obvious what the necessary width is, and it can indeed be a cumbersome solution.)
    – phils
    Commented Feb 8, 2018 at 21:10

1 Answer 1

4

You can do a replace-regexp like this:

  • replace ^\(.\{15\}\).*$
  • with \1

This will match lines with at least 15 characters, and replace with the 1st 15 (which are saved as a match group).

Did you mention that n=15?

2
  • 2
    E.g., (defun foo (beg end &optional n) (interactive "r\np") (let ((rgx (format "^\\(.\\{%d\\}\\).*$" n))) (replace-regexp rgx "\\1" nil beg end)))
    – Drew
    Commented Feb 8, 2018 at 20:55
  • @Drew your comment could be an independent answer.
    – Name
    Commented Feb 9, 2018 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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