dos2unix script

Hi Mikrotik fans!

Below is a simple dos2unix script where it removes the \r (carriage return) of a text file.

Useful for files or variable content in which you wish to remove the \r (CR)

    :local content $1
    :local cleanedContent ""
    :local start 0
    :local end 1

    # Loop through each character and remove '\r'
    :for i from=0 to=([:len $content]) step=1 do={
        :local char [:pick $content $start $end ]
        :local check [:find $char "\r"]
               :if ($check < 0 ) do={
            :set cleanedContent ($cleanedContent . $char)
        }
        :set start ($start + 1)
        :set end ($end +1)
}

:return $cleanedContent

Usage example for a text file when the above is saved at system scripts with name dos2unix

#Import the function from system scripts with name dos2unix
:local dos2unix [:parse [/system script get dos2unix source]]

#Load the content of the file, call the function and save the cleaned results to the file.
:local content [/file get test.txt contents]
:local cleanedContent [$dos2unix $content]
/file set test.txt contents=$cleanedContent

Or you can just clean the contents of the variable if you like.

ignoring others various errors,

why?

        :local check [:find $char "\r"]
               :if ($check < 0 ) do={
           :set cleanedContent ($cleanedContent . $char)
        }

just:

       :if ($char != "\r") do={:set cleanedContent "$cleanedContent$char"}

For some reason (maybe the mistake is from my side), the != “\r” was not working. I have the latest RoS

I will try again since you pointed that it should work that way ( and yes it should).

Thanks!

In the most recent V7 releases there are “:tocrlf” and “:tolf” commands available that do same as “dos2unix” (and reverse unix2dos). There is also now :convert, so we can see the effect those new commands do in hex (e.g. 0a == \n, 0d == \r):

:put [:convert from=raw to=hex [:tolf "0\r\n0\r\n"]]



300a300a


:put [:convert from=raw to=hex [:tocrlf "0\n0\n"]]



300d0a300d0a

For completeness, without the :tolf or :tocrlf:

:put [:convert from=raw to=hex "0\r\n0\r\n"]          
# 300d0a300d0a
:put [:convert from=raw to=hex "0\n0\n"]      
# 300a300a

Ah nice!

I will check that too!

Thanks for the info!