-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGrepCommand.java
More file actions
34 lines (31 loc) · 1.04 KB
/
GrepCommand.java
File metadata and controls
34 lines (31 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package IO;
import java.io.File;
import java.util.Scanner;
public class GrepCommand extends Command {
public GrepCommand() {
super("grep");
}
@Override
public void action(String[] cmd) {
if (cmd.length > 2) {
File file = new File(Main.wd, cmd[2]);
if (file.exists()) {
try (Scanner scanner = new Scanner(file)) {
String pattern = ".*" + cmd[1] + ".*";
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.matches(pattern)) {
System.out.println(line);
}
}
} catch (Exception e) {
System.out.println("Error reading file: " + e.getMessage());
}
} else {
System.out.println("File does not exist.");
}
} else {
System.out.println("Insufficient arguments. Usage: grep <pattern> <file>");
}
}
}