6 Replies - 301 Views - Last Post: 09 February 2012 - 02:34 PM Rate Topic: -----

Topic Sponsor:

#1 smokin_jim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 07-February 12

Question: attempting UNIX grep-like command in java

Posted 07 February 2012 - 04:42 PM

Hello,

I'm trying to create a java version of a UNIX script I have. In UNIX I can scan a file X, match a regexp pattern and then print the n^th word to the console (as defined by white spaces). With my java version, I have managed to pick my file using JFileChooser and read the file in as a string. I know the contents of the file have been read, because I can System.out.println and see the contents in the run window. This is what I have so far:

      
private void loadActionPerformed(java.awt.event.ActionEvent evt) { 
       try {
            Scanner params = new Scanner (file_path); 
            while (params.hasNext()){
            String test = params.nextLine();
            System.out.println(test); 
           
            }
            }
            catch (Exception e) {
            System.out.println("Error reading file");
            }



and from here on I'm stuck. The file I'm reading looks like:
##FNAME = Foo
##SNAME = Bar
##AGE = 20
##JOB = tobogganist 


etc...

As an end result I would ideally like a string of "Foo" or whatever based upon a search pattern like "##FNAME = "

Sorry if this is utterly mundane, I've only recently started using java. I have tried googling, but I'm just getting lost in pattern, matcher, scanner, bufferedreader ....... and I can't get anything I try to work.

Thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: Question: attempting UNIX grep-like command in java

#2 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1413
  • View blog
  • Posts: 6,037
  • Joined: 20-September 08

Re: Question: attempting UNIX grep-like command in java

Posted 07 February 2012 - 05:14 PM

Quote

	            Scanner params = new Scanner (file_path);
	            while (params.hasNext()){


Two things there:

a. 'file_path' needs to be of type File or it will be equivalent to
echo 'foo' | grep bar
b. That needs to be hasNextLine() - you want to read the file linewise

Quote

As an end result I would ideally like a string of "Foo"


Try

System.out.println(params.nextLine().replaceAll(".*\\b(.*)", "$1"));

This post has been edited by g00se: 07 February 2012 - 05:14 PM

Was This Post Helpful? 0
  • +
  • -

#3 smokin_jim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 07-February 12

Re: Question: attempting UNIX grep-like command in java

Posted 07 February 2012 - 06:46 PM

Thanks for the quick reply.

Yes I forgot to say I had indeed already declared my file_path of type file.

Ok, so I've changed
while (params.hasNext()){ 
to
while (params.hasNextLine()) {


But, when I try to use your print code:
System.out.println(params.nextLine().replaceAll(".*\\b(.*)", "$1"));

I seem to get only < > = " characters out. I've also tried tweaking your regexp, but I just keep getting the whole file printed out instead of just "foo".

Thanks.
Was This Post Helpful? 0
  • +
  • -

#4 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1413
  • View blog
  • Posts: 6,037
  • Joined: 20-September 08

Re: Question: attempting UNIX grep-like command in java

Posted 08 February 2012 - 03:09 AM

If you post your current code and attach a sample file, i'll take a look
Was This Post Helpful? 0
  • +
  • -

#5 smokin_jim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 07-February 12

Re: Question: attempting UNIX grep-like command in java

Posted 08 February 2012 - 12:09 PM

Ok, so here is the section of my code wrt two buttons (get & load)in my NetBeans GUI:

private File file_path;

private void GetActionPerformed(java.awt.event.ActionEvent evt)  {                                    
JFileChooser FC = new JFileChooser(""); 
FC.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);    

if (FC.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)  {
    file_path = FC.getSelectedFile();
                                                             }

                                                                 }                                   

private void LoadActionPerformed(java.awt.event.ActionEvent evt) {                                     
File acqu = new File(file_path, "acqu.txt");
        try {
            Scanner params = new Scanner (acqu); 
            while (params.hasNextLine()){

//The next 2 lines confirm (for me anyway) that the file is being read in, and that I can send the contents to a string which I can then read out. 
            //String test = params.nextLine();
            //System.out.println(test); 
     
System.out.println(params.nextLine().replaceAll(".*\\b(.*)", "$1"));
       
                                         }
            }
            catch (Exception e) {
            System.out.println("Error reading file");
                                }
 
        
                                                             }                       



The idea being that with the filechooser, the user will pick a directory for their project. I can then (by taking file_path) append there project directory to scan for particular variables across a number of files.

The file acqu.txt is what the above code will be relating too. I simplified a bit in the above example, but I thought the regex would be similar.

Cheers.
Was This Post Helpful? 0
  • +
  • -

#6 g00se  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1413
  • View blog
  • Posts: 6,037
  • Joined: 20-September 08

Re: Question: attempting UNIX grep-like command in java

Posted 08 February 2012 - 01:37 PM

Quote

The idea being that with the filechooser, the user will pick a directory for their project. I can then (by taking file_path) append there project directory to scan for particular variables across a number of files.


Why make the assumption that the file in question will be in the directory they choose? What you should do is let them simply choose a file. That way you can be sure that (unless they cancel) the File object is valid

And sorry- that pattern was wrong. It should be

System.out.println(params.nextLine().replaceAll(".* (.*)", "$1"));

This post has been edited by g00se: 08 February 2012 - 01:47 PM

Was This Post Helpful? 0
  • +
  • -

#7 smokin_jim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 07-February 12

Re: Question: attempting UNIX grep-like command in java

Posted 09 February 2012 - 02:34 PM

Ok, so thanks for the reply, but I still couldn't get the exact result I wanted. I have however solved the issue - although I'm sure those more experienced will think it's overkill for what I needed.

For those interested, my solution was to:

Include the following method at the start of my program:
  public static String substringBetween(String str, String open, String close) {
     if (str == null || open == null || close == null) {
          return null;
     }
      int start = str.indexOf(open);
      if (start != -1) {
          int end = str.indexOf(close, start + open.length());
          if (end != -1) {
              return str.substring(start + open.length(), end);
          }
      }
     return null;
  } 







Then, to obtain a particular substring of a string, I run the following whenever I need to extract something, in my example, when I pressed my "Load" button. I'm able to choose which exact substring because in my case, I know exactly 'how' the file will be laid out, so I simply use what will come before it (xyz) and what comes after (zyx) to form the boundaries of the extraction.

 private void LoadActionPerformed(java.awt.event.ActionEvent evt) {                                     
 try {  
String test = FileUtils.readFileToString(FILE);         
String extract = substringBetween(test, "xyz", "zyx");
		
             System.out.println("This has been extracted:" + extract); 
       
     }
            catch (Exception e) {
            System.out.println("Error reading file");
            }    
            }

//If the file originally read "xyzextractzyx", then "extract" will be read out. 



The only caveat is that I had to find the "apache.commons.io" jarfile, import it as a .JAR library into my netbeans project and then import it at the beginning of my program.

 import org.apache.commons.io.*; 


and I found that quite easily with google. This is by no means my work
I found it at: http://www.avajava.c...n-a-string.html

Thanks for your help though!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1