Posted by
| Nick Gammon
Australia (22,975 posts) bio
Forum Administrator |
Message
| This alias uses LPEG to handle the general case of converting files from Unix to DOS format, or vice-versa.
As described somewhere in the LPEG documentation, you can make a pattern that matches any of the standard line endings, namely:
Since this pattern matches any of the above, it will successfully find the line endings on any format file, without having to know in advance what format it is in.
The alias asks for an input file, and reads it in.
It then asks for the new line endings that you want (Dos, Mac, Unix) and then converts the line endings, reports the before and after sizes, and offers to save the converted data (press Esc to not save).
A modification of the general technique could be used to convert an entire directory.
You could also add additional line endings (for example, "<br>\n" to end each line).
<aliases>
<alias
match="file_convert"
enabled="y"
send_to="12"
sequence="100"
>
<send>
-- get input file
local inputname = utils.filepicker ("Choose file to convert")
if not inputname then return end
-- read input file
local f = assert (io.open (inputname, "rb"))
local s = f:read "*a"
f:close ()
-- four forms of delimiter
local delim = lpeg.P (lpeg.P("\\n") * "\\r") +
lpeg.P (lpeg.P("\\r") * "\\n") +
lpeg.P ("\\n") +
lpeg.P ("\\r")
-- conversion function
local function gsub (s, patt, repl)
patt = lpeg.P(patt)
patt = lpeg.Cs((patt / repl + 1)^0)
return lpeg.match(patt, s)
end
local choices = {
["\\n"] = "Unix (LF only)",
["\\r\\n"] = "Dos (CR/LF)",
["\\r"] = "Mac (CR only)",
} -- end choices
-- choose new line-ending type
local delimiter = utils.listbox ("Choose new line endings ...",
"Format of output file", choices, "\\r\\n")
if not delimiter then return end
-- convert line endings to new format
local converted = gsub (s, delim, delimiter)
-- show stats
print (string.format ("Input size (%%s) = %%i bytes (%%0.1f Kb).", inputname, #s, #s / 1024))
print ("Output size =", #converted, "bytes.")
-- ask to save
local outputname = utils.filepicker ("File name to save as", inputname, nil, nil, true)
if not outputname then return end
-- write it
local f = assert (io.open (outputname , "wb"))
assert (f:write (converted))
f:close ()
-- confirmation
print ("Done. Saved as:", outputname)
</send>
</alias>
</aliases>
|
- Nick Gammon
www.gammon.com.au, www.mushclient.com | top |
|