Skip to content

Commit

Permalink
Add simple grep example
Browse files Browse the repository at this point in the history
  • Loading branch information
angelcaru committed May 1, 2024
1 parent 182b7ce commit c837b1f
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions examples/simple-grep.rn
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import Argparser

fun main() {
parser = Argparser.Argparser()
parser.add_flag("--help", "-h", "Show this help text and exit")
parser.add_pos_opt("query", "String to query")
parser.add_pos_opt("file", "File to query string in")
parser.add_flag("--line-numbers", "-n", "Show line numbers")
parser.add_named("--max-lines", "Maximum amount of lines to show")
args = parser.parse(argv[:])

if args["--help"] {
print(parser.usage())
exit()
}

if is_null(args["query"]) {
parser.report_error(argv[0], "no query string provided")
}
if is_null(args["file"]) {
parser.report_error(argv[0], "no file provided")
}

f = File(args["file"], "r")
lines = (String(f.read())).split("\n")
f.close()

matched_lines = []
i = 0
for line in lines {
if args["query"] in line {
arr_append(matched_lines, [i, line])
}
nonlocal i++
}

if not is_null(args["--max-lines"]) {
nonlocal matched_lines = matched_lines[:int(args["--max-lines"])]
}

for line in matched_lines {
s = line[1]
if args["--line-numbers"] {
nonlocal s = args["file"] + ":" + line[0] + ": " + s
}
print(s)
}
}

main()

0 comments on commit c837b1f

Please sign in to comment.