3

Consider the following buffers

buffer_1:

11111111
22222222
33333333
44444444

buffer_2:

55555555
66666666
22222222
44444444

I need to remove all lines which are not equal in buffer_1 and buffer_2. The resulting buffer_3 must only contain equal lines, i.e. buffer_3 must be like this

22222222
44444444

The lines which where NOT EQUAL and are removed from buffer_2 are

55555555
66666666

Is it possible in Emacs?

5

In the following I assume that the order of the lines in the result buffer is irrelevant.

For medium size buffers you can use cl-intersection:

(defun txt-intersection (buffer-a buffer-b)
  "Only keep the set theoretic intersection of lines in BUFFER-A and BUFFER-B."
  (interactive "bBuffer A: \nbBuffer B: ")
  (with-current-buffer (generate-new-buffer (concat (buffer-name (get-buffer buffer-a))
                            "∩"
                            (buffer-name (get-buffer buffer-b))))
    (insert
     (mapconcat #'identity
        (cl-intersection
         (split-string
          (with-current-buffer buffer-a (buffer-string))
          "\n")
         (split-string
          (with-current-buffer buffer-b (buffer-string))
          "\n")
         :test #'string-equal)
        "\n"))
    (display-buffer (current-buffer))))

The second case is the analogous with intersection substituted by set-difference.

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.