A Nimrod version of the Linux head console command.
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()
jrs@laptop:~/nimrod/examples$ nimrod c -d:release nhead.nim
config/nimrod.cfg(36, 11) Hint: added path: '/home/jrs/.babel/libs/' [Path]
Hint: used config file '/home/jrs/nimrod/config/nimrod.cfg' [Conf]
Hint: system [Processing]
Hint: nhead [Processing]
Hint: parseopt [Processing]
Hint: os [Processing]
Hint: strutils [Processing]
Hint: parseutils [Processing]
Hint: times [Processing]
Hint: posix [Processing]
gcc -c -w -O3 -fno-strict-aliasing -I/home/jrs/nimrod/lib -o examples/nimcache/nhead.o examples/nimcache/nhead.c
gcc -c -w -O3 -fno-strict-aliasing -I/home/jrs/nimrod/lib -o examples/nimcache/parseopt.o examples/nimcache/parseopt.c
gcc -c -w -O3 -fno-strict-aliasing -I/home/jrs/nimrod/lib -o examples/nimcache/os.o examples/nimcache/os.c
gcc -c -w -O3 -fno-strict-aliasing -I/home/jrs/nimrod/lib -o examples/nimcache/strutils.o examples/nimcache/strutils.c
gcc -o /home/jrs/nimrod/examples/nhead examples/nimcache/posix.o examples/nimcache/times.o examples/nimcache/parseutils.o examples/nimcache/strutils.o examples/nimcache/os.o examples/nimcache/parseopt.o examples/nimcache/system.o examples/nimcache/nhead.o -ldl
Hint: operation successful (14375 lines compiled; 0.569 sec total; 15.158MB) [SuccessX]
jrs@laptop:~/nimrod/examples$ ./nhead -n=5 nhead.nim
import parseopt
from strutils import parseInt
from os import existsFile
const usage = """
jrs@laptop:~/nimrod/examples$
jrs@laptop:~/nimrod/examples$ ls -l nhead
-rwxrwxr-x 1 jrs jrs 67253 Sep 21 23:34 nhead
jrs@laptop:~/nimrod/examples$