Read a specific line of file

Read a specific line of file

  

Gurus

I want to read a specific line from a flat file, for instance I have flat file with 2MM lines and I want to read line #99. ( I do no want to load the file into memory with usual user action Read_text, etc)

Help will be deeply appreciate...


Hi Edgardo,

- Check what is the delimeter in your file to break the lines. (You can store file as resource or upload it at run time)

- After that use String_Split action from Text extension to split it as record which will return as list.


- After that use ListIndexOf to get particular element


Hope this helps.

Thanks and Regards,

Suraj Borade

What do you mean 2MM lines?

Is it 2 million lines?

Using String_Split from above answer could lead to performance issues.

It's best to find position of carriage return (CR) then use substr to cut the string.


To get #99 line, you would need to get position of 98th CR occurrence and 99th CR occurence.

Then use substr(text, 98th_CR+1, (99th_CR-98th_CR)+1)


You also need to account for the last line, is the last line has CR or not.

Harlin,

What about scenario where we want to pass line number dynamically?

If you have a flat-file and need just a specific line, I suggest to check a component in the forge or build it yourself.


Guys...You're answer is appreciate but again we are taking about 4MM records and I need retrieve the i-esimo without load all in the memory...

Harlin, you mentioned "

To get #99 line, you would need to get position of 98th CR occurrence and 99th CR occurence.

Then use substr(text, 98th_CR+1, (99th_CR-98th_CR)+1)"

May you elaborate the recommendation? How get the position?


Hello Edgardo,

Try using the following extension, that may help link.

Regards,

Sorry I was wrong.

You need to use C#/Java extension (depend on your platform stack) to do this.

Read file in block (Buffered) or stream, loop line by line while counting lines_read.

When lines_read = desired line number, then pass the line to output parameter.


For example in Java pre-8:

try(BufferedReader br = new BufferedReader(new FileReader(file))) {
    for(String line; (line = br.readLine()) != null; ) {
        // process the line.
    }
    // line is not visible here.
}


In Java 8:

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
        stream.forEach(System.out::println);
}