How to delete the specific lines that starts and ends with specific string in a file in java?

后端 未结 2 600
眼角桃花
眼角桃花 2021-01-17 02:47

I have a file abc.txt that has lines as

abc.txt

Ethernet 1/1 

Ethernet 1/2

interface 3

abs_mod_
jjj
kkkk
ll
abs_mod_

interface 6

interface 7
         


        
相关标签:
2条回答
  • 2021-01-17 03:15

    A naive approach:

    package test;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class ReadStringFromFileLineByLine {
    
        public static void main(String[] args) {
            try {
                File file = new File("abc.txt");
                FileReader fileReader = new FileReader(file);
                BufferedReader bufferedReader = new BufferedReader(fileReader);
                StringBuffer stringBuffer = new StringBuffer();
                String line;
                boolean flag = true;
                while ((line = bufferedReader.readLine()) != null) {
                    if(line.contains("abs_mod_")){
                        if(flag)    flag = false;
                        else        flag = true;
                    }else if(flag){
                        stringBuffer.append(line);
                        stringBuffer.append("\n");
                    }
                }
                fileReader.close();
                System.out.println("Contents of file:");
                System.out.println(stringBuffer.toString().replace("\n\n\n", "\n\n"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    Using regex:

    package test;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    
    public class ReadStringFromFileLineByLine {
    
        public static void main(String[] args) {
            try {
                File file = new File("abc.txt");
                FileReader fileReader = new FileReader(file);
                BufferedReader bufferedReader = new BufferedReader(fileReader);
                StringBuffer stringBuffer = new StringBuffer();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                    stringBuffer.append("\n");
                }
                fileReader.close();
                System.out.println("Contents of file:");
                System.out.println(
                    stringBuffer
                    .toString()
                    .trim()
                    .replaceAll("[\\n]+(abs_mod_)(\\s|\\S)*(abs_mod_)", "")
                );
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-17 03:28

    Load the entire file into memory, then use regex to remove the lines you don't want.

    Using Java 11+

    String text = Files.readString(Paths.get("abc.txt"));
    text = text.replaceAll("(?sm)^abs_mod_(?:.*?^abs_mod_)?.*?\\R", "");
    System.out.println(text);
    

    Using Java 7+

    String text = new String(Files.readAllBytes(Paths.get("abc.txt")), StandardCharsets.UTF_8);
    text = text.replaceAll("(?sm)^abs_mod_(?:.*?^abs_mod_)?.*?\\R", "");
    System.out.println(text);
    

    Output

    Ethernet 1/1 
    
    Ethernet 1/2
    
    interface 3
    
    
    interface 6
    
    interface 7
    

    Explanation

    (?              Set flags:
      s               DOTALL     '.' matches any character, including a line terminator
      m               MULTILINE  '^' and '$' match just after/before a line terminator
    )
    ^abs_mod_       Match 'abs_mod_' at beginning of line
    (?:             Start optional non-capturing group
      .*?             Match any text (including line terminators) until:
      ^abs_mod_         Match 'abs_mod_' at beginning of line
    )?              End optional section
    .*?             Match any text up to:
    \R                Match line terminator
    

    Both .* have the extra ? making them "reluctant", so they don't cross the "ending" match. The . in the second .*? won't actually match a line terminator since the ending match is a line terminator.

    The optional section is because you said: "delete the lines in between abs_mod_ and also lines starting with abs_mod_"

    The regex is really these two blended together:

    (?sm)^abs_mod_.*?^abs_mod_.*?\R   Lines between lines starting with 'abs_mod_' (inclusive)
    (?m:^)abs_mod_.*\R                Single line starting with 'abs_mod_'
    
    0 讨论(0)
提交回复
热议问题