lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Fri, Mar 4, 2011 at 11:39 AM, Dirk Laurie wrote:
> On Fri, Mar 04, 2011 at 10:14:28AM +0200, steve donovan wrote:

>> Thanks to my old friend awk, and a little editorial discretion:

> I wondered why your new friend lua could not also do it.

Using Lua in a pipe like that feels a little awkward (no pun intended.)

Hmmm....

-------------------------

#!/usr/bin/env lua

--[[

  lawk:
    A very crude awk-ish sort of Lua script, reads lines from stdin.

  First argument is a pattern to match against each line.
  If the first argument is an empty string, all lines match.

  Second argument is an operation to perform on the matched lines.
  If the second argument is an empty string, print(s0) is the default action.

  The input lines are tokenized similar to awk: The global variable
  s0 represents the entire line, s1 is the first token, s2 is the
  second token, etc...

  EXAMPLE: Print the names (in uppercase) of UDP protocols in /etc/services:

    lawk  '^[^#].*%d+/udp%s'  'print(s1:upper())'  < /etc/services

  TODO: ... ... ...

--]]



if #arg ~= 2 then
  io.stderr:write("Usage:\n  ", arg[0], " <pattern> <action>\n" )
  os.exit(1)
end


local __func = (#arg[2]==0)
  and function() print(s0) end
    or assert(loadstring(arg[2]), "Syntax error in command line")


for line in io.lines() do
  if line and line:find(arg[1]) then
    s0=line
    local i=1
    for token in s0:gmatch("[^%s]+") do
      _G["s"..i]=token
      i=i+1
    end
    if #arg[2]>0 then __func() else print(line) end
  end
end

-------------------------


 - Jeff