-- The cat utility reads files sequentially, writing them to the standard -- output. The file operands are processed in command line order. A single -- dash represents the standard input. -- -- The options are as follows: -- -- -b Implies the -n option but doesn't number blank lines. -- -- -e Implies the -v option, and displays a dollar sign (`$') at the -- end of each line as well. -- -- -n Number the output lines, starting at 1. -- -- -s Squeeze multiple adjacent empty lines, causing the output to be -- single spaced. -- -- -t Implies the -v option, and displays tab characters as `^I' as -- well. -- -- -u The -u option guarantees that the output is unbuffered. -- -- -v Displays non-printing characters so they are visible. Control -- characters print as `^X' for control-X; the delete character -- (octal 0177) prints as `^?' Non-ascii characters (with the high -- bit set) are printed as `M-' (for meta) followed by the character -- for the low 7 bits. -- -- The cat utility exits 0 on success, and >0 if an error occurs. require "getopt" function visualizechar(char,visualizetabs,visualizenewline) local code = string.byte(char) local tab = (code == 9) local newline = (code == 10) if (code < 32 and not tab and not newline) or (tab and visualizetabs) or (newline and visualizenewline) then -- replace with ^x replacement = "^" .. string.char(code - 1 + string.byte("A")) elseif (code == 127) then replacement = "^?" elseif (code >= 128) then -- replace with M-something replacement = "M-" .. visualizechar(string.char(code - 128),true,true) else replacement = char end return replacement end function visualize(options,line) line = string.gsub(line, ".", function (ch) return visualizechar(ch,options.t,false) end) if options.e then line = line .. "$" end return line end function cat(options,f) local lineno, inputfile, prevlineempty if f == "-" then inputfile = io.stdin else inputfile = io.open(f) end if options.n or options.b then lineno = 1 end local line = inputfile:read("*line") while line ~= nil do local lineempty = (line == "") if (not options.s) or not (lineempty and prevlineempty) then if options.v then line = visualize(options,line) end if options.n or (options.b and not lineempty) then io.write(string.format("%6d ",lineno),line,"\n") lineno = lineno + 1 else io.write(line,"\n") end if options.u then io.output():flush() end end prevlineempty = lineempty line = inputfile:read("*line") end inputfile:close() end options = getopt(arg, "benstuv") nfiles = arg.n -- -e, -t imply -v if (options.e or options.t) then options.v = 1 end table.remove(arg, 0) -- remove program name if nfiles == 0 then cat(options,"-") else for i = 0,nfiles-1 do cat(options,arg[i]) end end os.exit(0)