-- lua grep.lua [-hvcnli] PATTERN [FILE...] -- lua grep.lua [-hvcnli] -e PATTERN [FILE...] -- prints lines from FILEs which match PATTERN -- if no FILEs are given, stdin is used function toupper(ch) if (string.byte(ch) >= string.byte("a")) and (string.byte(ch) <= string.byte("z")) then return string.char(string.byte(ch) + string.byte("A") - string.byte("a")) else return ch end end function grepmatch(options, pattern, line) local result if options.i then pattern = string.gsub(pattern,"%l",toupper) line = string.gsub(line,"%l",toupper) end result = (string.find(line, pattern) ~= nil) if options.v then result = not result end return result end function grep(options, pattern, filehandle, filename) local lineno = 0 local matchcount = 0 local out for line in filehandle:lines() do lineno = lineno + 1 if grepmatch(options, pattern, line) then if options.l then print(filename) break elseif options.c then matchcount = matchcount + 1 else out = line if options.n then out = tostring(lineno) .. ":" .. out end if options.printnames then out = filename .. ":" .. out end print(out) end matched = true end end if options.c then out = tostring(matchcount) if options.printnames then out = filename .. ":" .. out end print(out) end end require "getopt" options = getopt(arg, "hvcne:li") argn = arg.n scriptname = arg[0] pattern = options.e or arg[1] files = arg table.remove(files, 0) -- remove program name table.remove(files, 0) -- remove pattern nfiles = argn - 1 options.printnames = (nfiles > 1) and (not options.h) matched = false if nfiles == 0 then grep(options, pattern, io.input(), "") else for i = 0, nfiles-1 do fh = io.open(files[i]) if fh == nil then print("error opening " .. files[i]) else grep(options, pattern, fh, files[i]) fh:close() end end end if matched then os.exit(0) else os.exit(1) end