-3

I have a Fixed length file, it is a large file with millions of records. The length of the record in each line is 19. In each line 12th character corresponds to a particular status for which I need to get the count of each status in the file. Eg:

XXXXXXXXXXX**1**XXXXXXXXX        
XXXXXXXXXXX**2**XXXXXXXXX      
XXXXXXXXXXX**3**XXXXXXXXX   
XXXXXXXXXXX**4**XXXXXXXXX

I need to do get the count of lines with 1 in 12th character of line, 2,3, and 4.

I'm using java as programming language.

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
normalindon1
  • 55
  • 1
  • 5
  • Did you try something on your own? – aleb2000 Dec 05 '16 at 15:30
  • @aleb2000: I tried this in terminal and find it to be working in terminal but I dont know how to do it from java. grep -c -e "^...........4" – normalindon1 Dec 05 '16 at 15:37
  • You say that the length of each line is 19 but your lines have a length of 21... – aleb2000 Dec 05 '16 at 16:19
  • If you're using java why did you tag it with awk? If you're happy with an awk solution why are you telling us you're using java? [edit] your question to clean that up and show a [mcve] including concise, testable sample input and expected output. – Ed Morton Dec 06 '16 at 01:22

2 Answers2

0

You can try to use Files class:

Files.lines(path_to_fle).filter(s -> s.charAt(11) == '1').count();

But probably it will be more efficient if you will use grep for this?

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
0

This is a bit longer than the one provided by @Anton.

public class Test {

    public static void main(String[] args) throws IOException {
        File file = new File("myfile.txt");
        String[] lines = Files.readAllLines(file.toPath()).toArray(new String[0]);
        lines = Arrays.stream(lines).map(l -> l.replaceAll("^.{11}(\\d).*$", "$1")).toArray(String[]::new);

        long n1 = Arrays.stream(lines).filter(s -> s.equals("1")).count();
        long n2 = Arrays.stream(lines).filter(s -> s.equals("2")).count();
        long n3 = Arrays.stream(lines).filter(s -> s.equals("3")).count();
        long n4 = Arrays.stream(lines).filter(s -> s.equals("4")).count();

        System.out.println("n1 = " + n1 + ", n2 = " + n2 + ", n3 = " + n3 + ", n4 = " + n4);
    }

}
aleb2000
  • 452
  • 4
  • 10