“A file is treated as a sequence of records, and by default each line is a record.” - Alfred V. Aho
awk 'BEGIN { print "Hello World!" }'
“Whenever faced with a problem, some people say `Lets use AWK.' Now, they have two problems.” - D. Tilbrook
BEGIN{split("a b c c a",a);for(i in a)b[a[i]]=1;r="";for(i in b)r=r" "i;print r}
nub $ words "a b c c a"
“A stream is treated as a sequence of records, and by default each line is a record.”
hawk '"Hello World!"'
> filter odd [1,2,3,4]
[1,3]
> let wordCount = sum . map (length . words) . lines
> :type wordCount
wordCount :: String -> Int
> wordCount "1 2 3\n4 5 6\n7 8 9"
9
> :type map
map :: (a -> b) -> [a] -> [b]
> :type not
not :: Bool -> Bool
> :type map not
map not :: [Bool] -> [Bool]
> map not [True,False]
[False,True]
$ hawk '1'
1
$ hawk '[1,2]'
1
2
$ hawk '[[1,2],[3,4]]''
1 2
3 4
$ echo '1\n2\n3' | hawk -a 'L.reverse'
3
2
1
$ echo '1 2\n3 4' | hawk -m 'L.reverse'
2 1
4 3
$ echo '1 2\n3 4' | hawk -a 'show'
[["1","2"],["3","4"]]
$ echo '1,2;3,4' | hawk -a -d',' -D';' 'show'
[["1","2"],["3","4"]]
$ echo '1 2\n3 4' | hawk -a -d'' 'show'
["1 2","3 4"]
$ echo '1 2\n3 4' | hawk -a -d'' -D'' 'show'
"1 2\n3 4\n"
class (Show a) => Rows a where
repr :: ByteString -> a -> [ByteString]
$ cat /etc/passwd | hawk -d: -m 'L.head'
root
daemon
...
$ cat /etc/passwd | hawk -d: -o'\t' -m '\l -> (l !! 0,l !! 2)'
root 0
daemon 1
...
$ cat /etc/passwd | hawk -d: -a 'L.sortBy (compare `on` L.head)'
bin:x:2:2:bin:/bin:/bin/sh
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
...
> cat /etc/passwd | hawk -ad: 'L.map (L.head &&& L.length) . L.group . L.sort . L.map L.last'
/bin/bash:1
...
$ cat ~/.hawk/prelude.hs
{-# LANGUAGE ExtendedDefaultRules, OverloadedStrings #-}
import Prelude
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.List as L
$ echo 'takeBetween s e = L.take (e - s) . L.drop s' >> ~/.hawk/prelude.hs
$ seq 0 100 | hawk -a 'takeBetween 2 4'
2
3
hawk '[1..]' | hawk -a 'L.take 3'
> import Language.Haskell.Exts.Parser
> getTopPragmas "{-# LANGUAGE NoImplicitPrelude,OverloadedStrings #-}\n"
ParseOk [LanguagePragma (SrcLoc
{srcFilename = "unknown.hs", srcLine = 1, srcColumn = 1})
[Ident "NoImplicitPrelude",Ident "OverloadedStrings"]]
> import Language.Haskell.Interpreter
> runInterpreter $ setImports ["Data.Int"] >> interpret "1" (as :: Int)
Right 1
> runInterpreter $ setImports ["Data.Int"] >> interpret "foo" (as :: Int)
Left (WontCompile [GhcError {errMsg = "Not in scope: `foo'"}])