P basak
P basak

Reputation: 5004

extracting particular lines java

I have a text file just like below

add device 1: /dev/input/event7
  name:     "evfwd"
add device 2: /dev/input/event6
  name:     "aev_abs"
add device 3: /dev/input/event5
  name:     "light-prox"
add device 4: /dev/input/event4
  name:     "qtouch-touchscreen"
add device 5: /dev/input/event2
  name:     "cpcap-key"
add device 6: /dev/input/event1
  name:     "accelerometer"
add device 7: /dev/input/event0
  name:     "compass"
add device 8: /dev/input/event3
  name:     "omap-keypad"
4026-275085: /dev/input/event5: 0011 0008 0000001f
4026-275146: /dev/input/event5: 0000 0000 00000000
4026-494201: /dev/input/event5: 0011 0008 00000020
4026-494354: /dev/input/event5: 0000 0000 00000000

what i need to do is i want to remove the add device preambles, i just need the lines starting from 4026-275... that is,

    4026-275085: /dev/input/event5: 0011 0008 0000001f
    4026-275146: /dev/input/event5: 0000 0000 00000000
    4026-494201: /dev/input/event5: 0011 0008 00000020
    4026-494354: /dev/input/event5: 0000 0000 00000000

now this numbers can vary. How can I extract this efficiently. the preambles line numbers are not constant.

Upvotes: 0

Views: 149

Answers (4)

Joost
Joost

Reputation: 3209

If it is always the case that the lines you need start with a number, you can check whether this is the case using something like the following.

String[] lines = figureOutAWayToExtractLines();

// Iterate all lines
for(String line : lines)
    // Check if first character is a number (optionally trim whitespace)
    if(Character.isDigit(str.charAt(0)))
        // So something with it
        doSomethingWithLine(line);

Upvotes: 0

Doug
Doug

Reputation: 380

Try with a regular expression :

boolean keepLine = Pattern.matches("^\d{4}-\d{6}.*", yourLine);

Upvotes: 0

Anay Tamhankar
Anay Tamhankar

Reputation: 79

Read the text file line by line. For each line if the String startsWith "add device" or startsWith "\tname:" then simply ignore those lines. For example:

final String line = reader.readLine();
if(line != null) {
    if(line.startsWith("add device") || line.startsWith("\tname:")) {
        // ignore
     }
     else {
        // process
     }
}

Upvotes: 0

Ridcully
Ridcully

Reputation: 23655

Just keep only the lines beginning with a digit.

for (String line : lines) {
    if (line.matches("^\\d+.*")) {
        System.out.println("line starts with a digit");
    }
}

Upvotes: 1

Related Questions