Saturday, July 11, 2009

Windows unix cut command - column cut mode

The second part of the Windows Unix Cut command implements the column cut mode of the Cut command. By specifying flags such as -c for column cut mode and -p for entire file cut mode, the program can be used to cut the file based on column and file respectively.

This functionality is available in Editplus which offers column select option, but the command line tool can be very useful while cutting enormous files. The latest code is given below:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Cut {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(args[1]);
out = new FileOutputStream("cutoutput.txt");
if(args[0].equals("-p")){
int c,count=0,llim=Integer.parseInt(args[2]),ulim=Integer.parseInt(args[3]);
while ((c = in.read()) != -1) {
if((char)c=='\n'){
count =count-1;}
count++;
if(count>=llim && count<=ulim){
//System.out.println((char)c);
out.write(c);}
}
System.out.println("Total characters between range is "+(ulim-llim));
}
else if(args[0].equals("-c")){
int c,count=0,llim=Integer.parseInt(args[2]),ulim=Integer.parseInt(args[3]);
while ((c = in.read()) != -1) {
if((char)c=='\n'){
count =1;out.write('\n');/*System.out.println();*/}
count++;
if(count>=llim && count<=ulim){
//System.out.print((char)c);
out.write(c);}
}
System.out.println("Output to be viewed in Wordpad or higer only" );
}

} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}