Search code examples
lispcommon-lispclisp

How to remove line from file in LISP?


I'm currently trying to remove lines from a file using LISP.

(defun remove_line_from_file (file line_number)
    
)

(defun remove_lines_from_file (file lines)
    (if (not (null lines))
        (progn
            (remove_line_from_file (file (car (sort lines #'>))))
            (remove_lines_from_file (file (cdr (sort lines #'>))))
        )
    )
)

I have no idea how I can do that. What I did was the recursion.

An example of call:

(remove_lines_from_file "file_name" (2 3 5 6))

How can I delete a specified line from a file?

(remove_line_from_file "file_name" 2)

Solution

  • Notes:

    1. snake_case is not Lispy, use lisp-case (a.k.a. kebab case)
    2. sort mutates its argument, so in your case it has side-effects on the input list; you would need to do (sort (copy-list list) ...) instead.
    3. you seem to be trying to recurse on lines, which looks like it would be inefficient; you probably want to iterate over the file once

    You need to open the file for reading, iterate over all lines while incrementing a line counter, and copy each line (e.g. write to standard output) except when the line number is one of the lines to remove:

    (defun remove-lines (file lines-to-remove)
      (with-open-file (in file)
        (loop
          for line-number from 1
          for line = (read-line in nil nil)
          while line
          unless (member line-number lines-to-remove)
            do (write-line line))))