Skip to content

Instantly share code, notes, and snippets.

@haruyama
Created January 21, 2013 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haruyama/4583517 to your computer and use it in GitHub Desktop.
Save haruyama/4583517 to your computer and use it in GitHub Desktop.
import System.Environment
import System.IO
import System.Exit
import Control.Monad (filterM)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.ICU.Regex as TIR
import qualified Data.Text.Lazy.IO as TILO
main :: IO ()
main = do
args <- getArgs
if length args < 1
then do
hPutStrLn stderr "Usage: mygrep pattern [file1] [file2] ..."
exitWith (ExitFailure 1)
else
do
reg <- TIR.regex [] (T.pack . head $ args)
if length args == 1
then doesGrepLinesFromHandle reg stdin
else
mapM_ (\fn ->
withFile fn ReadMode $ \inh ->
doesGrepLinesFromHandle reg inh) $ drop 1 args
exitSuccess
matchesLine:: TIR.Regex -> TL.Text -> IO Bool
matchesLine reg line =
do
TIR.setText reg $ TL.toStrict line
TIR.find reg 0
doesGrepLinesFromHandle:: TIR.Regex -> Handle -> IO ()
doesGrepLinesFromHandle reg inh =
do
contents <- TILO.hGetContents inh
filtered <- filterM (matchesLine reg) $ TL.lines contents
mapM_ TILO.putStrLn filtered
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment