如何从.log文件中删除某些列/元素



我想删除某些日志条目来解析文件。但是,在运行BufferedReader和其他导入的函数和库时,我从使用. replaceall方法运行的代码中得到了错误。如何在不引起错误的情况下删除"rule_uid: {C1336766-9489-4049-9817-50584D83A245}"?

日志文件:

Jan 1 22:54:17 drop   %LOGSOURCE% >eth1 rule: 7; rule_uid: {C1336766-9489-4049-9817-50584D83A245};
Jan 1 22:54:22 drop   %LOGSOURCE% >eth1 rule: 7; rule_uid: {C1336766-9489-4049-9817-50584D83A245};
Jan 1 22:54:23 drop   %LOGSOURCE% >eth1 rule: 7; rule_uid: {C1336766-9489-4049-9817-50584D83A245};
Jan 1 22:54:41 drop   %LOGSOURCE% >eth1 rule: 7; rule_uid: {C1336766-9489-4049-9817-50584D83A245};
错误:

"Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 9
rule_uid: {C1336766-9489-4049-9817-50584D83A245};" (which is at the .replaceAll() method for rule_uid column)
代码:

try {
        File file = new    File("filename");
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line = "", oldtext = "";
        while ((line = reader.readLine()) != null) {
            oldtext += line + "rn";
        }
        reader.close();
        // replace a word in a file
        String newtext = oldtext.replaceAll("%LOGSOURCE% >eth1 rule: 7;", "");
        String newtext1 = oldtext.replaceAll("rule_uid: {C1336766-9489-4049-9817-50584D83A245};", "");
     //To replace a line in a file
        FileWriter writer = new FileWriter("newfilename");
        writer.write(newtext);
        writer.write(newtext1);
        writer.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

在第二次调用replaceAll()的输入字符串中有特殊字符,这些字符被解释为正则表达式语法的一部分,而不是要替换的纯文本。一旦我转义了IntelliJ中的这些特殊字符,编译器错误就消失了。

改变:

String newtext = oldtext.replaceAll("%LOGSOURCE% >eth1 rule: 7;", "");
String newtext1 = oldtext.replaceAll("rule_uid: {C1336766-9489-4049-9817-50584D83A245};", "");

:

String newtext = oldtext.replaceAll("%LOGSOURCE% >eth1 rule: 7;", "");
String newtext1 = oldtext.replaceAll("rule_uid: \{C1336766-9489-4049-9817-50584D83A245\};", "");

我所做的只是用两个前导反斜杠转义大括号,例如\{

更新:

您的代码中还有其他一些逻辑问题。下面是我建议您使用的完整代码:

try {
    File file = new File("filename");
    BufferedReader reader = new BufferedReader(new FileReader(file));
    String line = "", oldtext = "";
    while ((line = reader.readLine()) != null) {
        oldtext += line + "rn";
    }
    reader.close();
    // replace a word in a file
    oldtext = oldtext.replaceAll("%LOGSOURCE% >eth1 rule: 7;", "");
    oldtext = oldtext.replaceAll("rule_uid: \{C1336766-9489-4049-9817-50584D83A245\};", "");
    FileWriter writer = new FileWriter("newfilename");
    // the entire file is contained within the String 'oldtext'
    // you only need one write operation to output it
    writer.write(oldtext);
    writer.close();
} catch (IOException ioe) {
    ioe.printStackTrace();
}

相关内容

  • 没有找到相关文章

最新更新