/*
* Globally match regular expression and print
* Modelled after the Unix command with the same name
* D. Spinellis, January 2004-2024
*/
import java.util.regex.*;
import java.io.*;
class Grep {
public static void main(String args[]) {
if (args.length != 2) {
System.err.println("Usage: Grep pattern file");
System.exit(1);
}
try (var in = new BufferedReader(new InputStreamReader(
new FileInputStream(args[1])))) {
Pattern compiledRe = Pattern.compile(args[0]);
String s;
while ((s = in.readLine()) != null) {
Matcher m = compiledRe.matcher(s);
if (m.find())
System.out.println(s);
}
} catch (FileNotFoundException e) {
System.err.println("Unable to open file " + args[1] + ": " + e.getMessage());
System.exit(2);
} catch (PatternSyntaxException e) {
System.err.println("Invalid RE syntax: " + e.getDescription());
System.exit(3);
} catch (IOException e) {
System.err.println("Error reading line: " + e.getMessage());
System.exit(4);
}
}
}