Created
January 21, 2013 04:03
-
-
Save haruyama/4583517 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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