1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.regex.Matcher;
  7. import java.util.regex.Pattern;
  8. public class LogSearch {
  9. public static List<String> searchLogFiles(String logFilePath, String searchPattern) {
  10. List<String> results = new ArrayList<>();
  11. Pattern pattern = Pattern.compile(searchPattern); // Compile the regex pattern
  12. try (BufferedReader reader = new BufferedReader(new FileReader(logFilePath))) {
  13. String line;
  14. int lineNumber = 0;
  15. while ((line = reader.readLine()) != null) {
  16. lineNumber++;
  17. Matcher matcher = pattern.matcher(line); // Match the pattern in the current line
  18. if (matcher.find()) {
  19. results.add("Line " + lineNumber + ": " + line); // Add the matching line to the results
  20. }
  21. }
  22. } catch (IOException e) {
  23. System.err.println("Error reading log file: " + e.getMessage());
  24. }
  25. return results;
  26. }
  27. public static void main(String[] args) {
  28. if (args.length != 2) {
  29. System.out.println("Usage: java LogSearch <logFilePath> <searchPattern>");
  30. return;
  31. }
  32. String logFilePath = args[0];
  33. String searchPattern = args[1];
  34. List<String> results = searchLogFiles(logFilePath, searchPattern);
  35. if (results.isEmpty()) {
  36. System.out.println("No matches found.");
  37. } else {
  38. for (String result : results) {
  39. System.out.println(result);
  40. }
  41. }
  42. }
  43. }

Add your comment