40 import java.io.IOException;
41 import java.io.UncheckedIOException;
42 import java.nio.file.Files;
43 import java.nio.file.Path;
44 import java.nio.file.Paths;
45 import java.util.Arrays;
46 import java.util.List;
47 import java.util.regex.Pattern;
48 import java.util.stream.Stream;
50 import static java.util.stream.Collectors.toList;
70 System.out.println(
"Usage: " +
Grep.class.getSimpleName()
71 +
" [OPTION]... PATTERN FILE...");
72 System.out.println(
"Search for PATTERN in each FILE. "
73 +
"If FILE is a directory then whole file tree of the directory"
74 +
" will be processed.");
75 System.out.println(
"Example: grep -m 100 'hello world' menu.h main.c");
76 System.out.println(
"Options:");
77 System.out.println(
" -m NUM: stop analysis after NUM matches");
78 Arrays.asList(str).forEach(System.err::println);
89 public static void main(String[] args)
throws IOException {
90 long maxCount = Long.MAX_VALUE;
91 if (args.length < 2) {
96 while (args[i].startsWith(
"-")) {
100 maxCount = Long.parseLong(args[++i]);
101 }
catch (NumberFormatException ex) {
111 Pattern pattern = Pattern.compile(args[i++]);
112 if (i == args.length) {
127 List<Path> files = Arrays.stream(args, i, args.length)
131 .filter(Files::isRegularFile)
142 files.parallelStream()
145 .filter(pattern.asPredicate())
147 .forEachOrdered(System.out::println);
148 }
catch (UncheckedIOException ioe) {
164 return Files.walk(
path);
165 }
catch (IOException e) {
166 throw new UncheckedIOException(e);
180 return Files.lines(
path);
181 }
catch (IOException e) {
182 throw new UncheckedIOException(e);