Clojure - Is it possible to increase a variable in a dose instruction?

I am trying to iterate over a list of files in a given directory and add an extra variable i = {1,2,3 .....} to their names.

Here is the code that I have for iterating over files and changing the name of each file:

(defn addCounterToExtIn [d]
  (def i 0)
  (doseq [f (.listFiles (file d)) ] ; make a sequence of all files in d
    (if (and (not (.isDirectory f)) ; if file is not a directry and
             (= '(\. \i \n) (take-last 3 (.getName f))) ) ; if it ends with .in
      (fs/rename f (str d '/ i (.getName f)))))) ; add i to start of its name

I do not know how I can increase i, as doseqiterates through each file. Alternatively, is there a better cycle to achieve the desired result?

+3
source share
2 answers

use file-seqand map-indexed:

(require '[clojure.java.io :as io])

(dorun
  (->>
    (file-seq (io/file "/home/eduard/Downloads"))
    (filter #(re-find #".+\.pdf$" (.getName %)))
    (map-indexed (fn [i v] [i v]))))

Change the function to map-indexedto rename and you're done. Example output for pdf files:

([0 #<File /home/eduard/Downloads/some.pdf>] ...)
+8
source

. , , , , , .

(def rename-one-file! [file counter]
  (if (and (not (.isDirectory file))
           (= ".in" (str (take-last 3 (.getName file)))))
      (fs/rename file (file (parent dir)
                            (str counter (.getName file)))))


(defn iterate-files-with-counter [fn dir]
  (loop [counter 0
         remaining-files (.listFiles (file dir))]
    (let [current-file (first remaining-files)]
      (fn file counter)
      (recur (+ counter 1) (rest remaining-files))))

(def add-counter-to-ext-in-dir
  (partial iterate-files-with-counter rename-one-file!))

, . , , /, , , .

+3

All Articles