1 using System;
2 using System.IO;
3 using System.Collections;
4 using System.RegularExpressions;
5
6 void PrintHelp()
7 {
8 Console.Out() << "Usage: sgrep \"PATTERN\" FILES..." << endl();
9 }
10
11 int main(int argc, const char** argv)
12 {
13 try
14 {
15 ustring pattern;
16 List<string> fileNames;
17 for (int i = 1; i < argc; ++i;)
18 {
19 string arg = argv[i];
20 if (arg.StartsWith("--"))
21 {
22 if (arg == "--help")
23 {
24 PrintHelp();
25 return 1;
26 }
27 else
28 {
29 throw Exception("unknown option '" + arg + "'");
30 }
31 }
32 else if (arg.StartsWith("-"))
33 {
34 for (char o : arg)
35 {
36 if (o == 'h')
37 {
38 PrintHelp();
39 return 1;
40 }
41 else
42 {
43 throw Exception("unknown option '-" + string(o) + "'");
44 }
45 }
46 }
47 else
48 {
49 if (pattern.IsEmpty())
50 {
51 pattern = u".*" + ToUtf32(arg) + u".*";
52 }
53 else
54 {
55 fileNames.Add(arg);
56 }
57 }
58 }
59 Context context;
60 Nfa nfa = CompileRegularExpressionPattern(context, pattern);
61 for (const string& fileName : fileNames)
62 {
63 Console.Out() << fileName << ":" << endl();
64 List<string> lines = File.ReadAllLines(fileName);
65 long n = lines.Count();
66 for (long i = 0; i < n; ++i;)
67 {
68 ustring line = ToUtf32(lines[i]);
69 if (PatternMatch(line, nfa))
70 {
71 Console.Out() << ToString(i + 1) << ": " << line << endl();
72 }
73 }
74 }
75 }
76 catch (const Exception& ex)
77 {
78 Console.Error() << ex.Message() << endl();
79 return 1;
80 }
81 return 0;
82 }