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
  • Try rectangle editing. – Dan Feb 8 '18 at 18:52
  • rectangle editing misses segments when some lines in the middle are lengthy – american-ninja-warrior Feb 8 '18 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 Feb 8 '18 at 21:10
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
    E.g., (defun foo (beg end &optional n) (interactive "r\np") (let ((rgx (format "^\\(.\\{%d\\}\\).*$" n))) (replace-regexp rgx "\\1" nil beg end))) – Drew Feb 8 '18 at 20:55
  • @Drew your comment could be an independent answer. – Name Feb 9 '18 at 13:40

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.