Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A simple implementation of `head` in Nimrod
import parseopt
from strutils import parseInt
from os import existsFile
const usage = """
head [flags] filename
-n: number of lines (default 10)
-h,--help: this help
-v,--version: version
"""
proc showUsage(msg: string) =
if msg != nil: echo("head: ",msg)
quit(usage,1)
proc head(file: string, n: int) =
if not existsFile(file): quit("file " & file & " does not exist")
var
f = open(file)
i = 0
for line in f.lines:
echo(line)
i += 1
if i == n: break
proc parseCommands() =
var
files: seq[string]
n = 10
newSeq(files,0)
for kind, key, val in getopt():
case kind
of cmdArgument:
files.add(key)
of cmdLongOption, cmdShortOption:
case key
of "help", "h": showUsage(nil)
of "n":
n = parseInt(val)
of "version", "v":
echo("1.0")
return
of cmdEnd: assert(false) # cannot happen
if len(files) == 0:
# no filename has been given, so we show the help:
showUsage("please supply filename")
if len(files) == 1:
head(files[0],n)
else:
for f in files:
echo("----- ",f)
head(f,n)
parseCommands()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment