Skip to content

Instantly share code, notes, and snippets.

@yujihamaguchi
Last active August 29, 2015 14:05
Show Gist options
  • Save yujihamaguchi/b1564b7ae345494069b7 to your computer and use it in GitHub Desktop.
Save yujihamaguchi/b1564b7ae345494069b7 to your computer and use it in GitHub Desktop.
[Haskell] grepコマンド自作
--[grep] 標準入力について、文字列パターンに一致する部分を持つ行を出力する。
-- [Usage] grep {pattern(regex)}
import System
import Text.Regex.Posix
main = do cs <- getContents
args <- getArgs
putStr $ unlines $ filter (¥str -> contain (head args) str) $ lines cs
contain :: String -> String -> Bool
contain cs cs' = cs' =‾ cs :: Bool
--[grep2] カレントディレクトリで、ファイル名パターンに一致したファイルについて、文字列パターンに一致する部分を持つ行を出力する。”ファイル名: 行”の形で出力する。
-- [Usage] grep2 {pattern(regex)} {file name pattern(regex)}
import Directory
import Control.Monad
import Data.List
import Text.Regex.Posix
import System
fileNameWidth = 35
main = do args <- getArgs
do getCurrentDirectory
>>= getDirectoryContents
>>= mapM (grep (head args)) . filter (¥n -> n =~ (head (tail args)) :: Bool)
>>= return . (¥_ -> "")
>>= putStrLn
grep :: String -> String -> IO ()
grep tg f = flip catch
(return . const ())
(do cs <- readFile f
let ls = filter (¥str -> str =~ tg :: Bool) $ lines cs
putStr $ unlines $ map (¥str -> f ++ (replicate (fileNameWidth - length f) ' ') ++ ": " ++ str) ls
return ())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment