1 September 2019
How to remove ANSI escape sequences in Clojure
Problem
You run command remotely using the library like clj-ssh
which allow you to run command against remote server and get the result back as string.
The result output that you get will contain escape character that you don't want to use. So you like to remove it to keep only the normal text for further processing.
Solution
Leverage the power of lambdaisland/ansi library which allow you to parse and escape the sequence to Hiccup syntax which is very easy to deal with.
The code that does the magic are the following
(require '[lambdaisland.ansi :refer [text->hiccup]])
;; I create the follwing function that does the cleanup
(defn clean-ansi [text]
(map last (text->hiccup text)))
If you have the following setup:
;; given that we have the following input
(def text "\033[1m here \033[45m we \033[31m go! \033[0m done.")
;; And the result of applying the function
(ansi/text->hiccup text)
;;=>
([:span {:style {:font-weight "bold"}} " here "]
[:span {:style {:background-color "rgb(205,0,205)", :font-weight "bold"}}
" we "]
[:span {:style {:color "rgb(205,0,0)",
:background-color "rgb(205,0,205)",
:font-weight "bold"}}
" go! "]
[:span {} " done."])
;; Then we can get just the plain result with
(clean-ansi text)
;;=> (" here " " we " " go! " " done.")