Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Select lines from .txt file

Status
Not open for further replies.

level1

Programmer
Apr 16, 2002
60
GB
Can you help please?

I have a text file ".txt" and i want to specify lines to read from it in command line.

i.e

my.txt contains

Line 1 of text
Line 2 of text
Line 3 of text
Line 4 of text
Line 5 of text
Line 6 of text



Input

Java LineReader 3,5
or
Java LineReader 3 5



Output

Line 3 of text
Line 4 of text
Line 5 of text

I Hope its easy
 
i forgot to mention the correct input includes the file name i.e:

Java LineReader my.txt 3 5

please help
 
look into the java-docs, package: java.io, BufferedLineReader or LineReader should be the classname of first choice.

On linux, you would simply call:
cat my.txt | head 5 | tail 3
which is on windows:
type my.txt | <missing> 5 | <missing> 3

Which means, there is no command 'head' or 'tail' to give you the first or last n lines.
No command shipped with windows.
But the 'gnutils'-package could contain them.
 
I finally found some script and simply modifided it to fit the purpose. Thanks stefanwagner for you help. The following code accepts the text file plus two numbers on command line.

usage:

java SelectLines my.txt 2 4

Output

line 2 of file
line 3 of file
line 4 of file



import java.io.*;

// Illustrate the LineNumberReader class.
class SelectLines {
public static void main(String[] args){
int n = 0;

int Line1;
int Line2;
// if statement to verify if the text file argument has been specified by the user

if(args.length > 0){
Line1 = Integer.parseInt(args[1]);
Line2 = Integer.parseInt(args[2]);

final int whichLine = 1;

for(n = 0; n < args.length; n++){

try {

selectLines(args[n], whichLine, Line1, Line2);
}
catch (Exception e) {
}
}

}

else{
// No file names were given.
System.out.println("Usage: "+"java SelectLines file ...");
}
}

public static void selectLines(String filename, int n, int L1, int L2)
throws FileNotFoundException, IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
// Read the first line.
String line = reader.readLine();


while(line != null){

int lineNo = reader.getLineNumber();
// if((reader.getLineNumber() % n) == 0) {
//for(lineNo = 3; lineNo < 4; lineNo++){
if (((lineNo) >= L1) && ((lineNo) <= L2)) {
System.out.println(line);
}
line = reader.readLine();


}
reader.close();
}

}


Now i have another puzzle to solve:)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top