Search a string in file

I want to search for a string in file. I can do it reading the file in line by line and search each line but that would be more expensive. Is there are any api/freeware library, which can help me to search for a string in file?
- R

You can eliminate the overhead of creting strings, and also of translating bytes to chars, but that's all you can do. Do not forget:
Premature optimization is the root of all evil.
Using ByteBuffer and java.nio could be the best. I do not believe there's a library doing exactly what you need - I suppose nobody really needs it and it's easy to do.

Similar Messages

  • Searching for string in text files on XP

    Hi,
    At the moment I'm working on a Struts program. The output I get is:
    The requested resource (Invalid path /displayAddProductForum was requested) is not available.Somewhere in my files, I have a line containing /displayAddProductForum that should be displayAddProductForm. As I'm using XP as my development platform, I use the 'Windows Explorer' search facility. And I have noticed this search facility does not look in .java, .jsp and any other file with a non-Microsoft file-extension. So, how do you search for a string in a source file on XP?
    Abel

    sabre150 wrote:
    kajbj wrote:
    sabre150 wrote:
    Abel wrote:
    , I use the 'Windows Explorer' search facility. And I have noticed this search facility does not look in .java, .jsp and any other file with a non-Microsoft file-extension. So, how do you search for a string in a source file on XP? Err.. On my XP it does search though java/jsp files if I tell it to!You mean by modifying the registry?No! Using the right mouse click on a directory to get a context menu -> Search -> (All or part of filename : .java ) and (A word or phrase in the file : blah blah blah) -> Search
    Edit : Errr.. maybe I'm talking rubbish because I have just tested this and it only finds 5 java files of mine that contain the word 'class'! I'm sure it used to work because in my 'Windows' days I frequently used it.
    Edited by: sabre150 on Dec 20, 2007 12:44 PMSounds a bit odd. Search in windows should only search in registered file types and neither jsp nor java are registered types. It's however possible to modify the registry and add extensions (but it's not possible to say search within all types of files, and that sucks)

  • Search a string with in some file and get the name of file

    i want to search a string in some files that are in a given directory and return the name of file having searched string.I am doing this with grep command as given below
    import java.io.*;
    public class linux_java {
    public static void main(String[] args) {
    try {
    String command = "find . | xargs grep -l Resolv /data2/opt/jakarta-tomcat-4.1.24/webapps/Oa/BOG/*.txt";
    final Process process = Runtime.getRuntime().exec(command);
    OutputStream os= process.getOutputStream();
    System.out.println("out put stream= " +os);
    PrintStream stdIn = new PrintStream(new BufferedOutputStream(process.getOutputStream()), true);
    System.out.println("Return code = " + stdIn);
    } catch (Exception e) {
    e.printStackTrace();
    i dont know how to get the name of file that are return by the execution of command through process object. Please send the code for the same

    thanks for your suggestion....
    i change the code but now it is giving error as /usr/bin/find incomplete syntax....but i am giving the right syntax....
    please confirm whether the syntax is correct...
    import java.io.*;
    import java.util.*;
    public class linux_java {
    public static void main(String[] args) {
    try {
    //String command = "ls -alt";
    String command = "find /data2/opt/jakarta-tomcat-4.1.24/webapps/Oa/BOG -type f -exec grep -sl 'Aggarwal' {} \\; 2>/dev/null";
    ///grep -l System test/*java
    System.out.println(" the command is"+command);
    final Process process = Runtime.getRuntime().exec(command);
    InputStream is = process.getErrorStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line="";
    System.out.println(" the BufferedReader is"+br.readLine());
    while ((line = br.readLine()) != null) {
    System.out.println(" the files are"+line);
    } catch (Exception e) {
    e.printStackTrace();
    }

  • Increasing the speed of searching a string in a file

    I have to search a String in a big ASCII-file and have to delete it. Now I wrote a program which opens the source file and a target file. I am reading each line from the source file, check it and write it into the target file. It is working fine but it is very slowly.
    I check each line with:
    if (line.equalsIgnoreCase("xxxxx")) { }
    How can I make it much faster.
    Thank you for your help!
    Arthur

    IO is an issue, but I've noticed that changing the case of strings is very slow, probably because in unicode is harder than in ASCII.
    If you could replace the equalsIgnoreCase method by one or more equals, you'll get benefits. If you can, I would try something like the following to minimize the equalsIgnoreCase invocations:
    // Supose you are looking for "abcd"
    if (line.charAt(0) == 'a' || line.charAt(0) == 'A') {
       if (line.equals("xxxxx")) { }
    }Try it and let us know if it worth the effort.

  • How to search a string in some folder.

    Hi ,
    In my application users will upload some pdf,xls files to server. files will be saved in server. From the front end can search on all files with some specific string. If that string is there in any of the file, user has to get link to download that file and the text just before and after that user string. Its like how we get in google. This type of search we need to implement, Could any one please let me know how to implement, any free API are there in java. Please its urgent, help on this.
    Thanks
    Mohan

    user594301 wrote:
    I have 2 columns in a table. entry_no and msg_txt. entry_no is number(12) and msg_txt is LONG. I want to search one string in msg_txt. How can I write a query for this ?You can't write a query for this. The only thinks you can do with a long in a query is put something in and take it out again - with diffiuclty, usually.
    You can write a PL/SQL function to do this for you if necessary. The function will have to perform the search directly if the long < 32760 bytes or use DBMS_SQL to break the LONG up into 32760 byte segments that can then be manually searched. If you are lucky someone has done this already and posted the code online. Either way the solution will be slow and probably painful to implement.
    If possible convert your data to a CLOB and use DBMS_CLOB to find the data you need.

  • Searching for a particular file

    Hi
    I know the file name is odbc.ini and i know the drive name is c:
    And how do i get the path of the file through program.
    Thanx in advance.
    Subhas

    public static String retrieveFile() throws IOException{
              String s = "odbc.ini";
                   String path = recursiveSearch(new File("c:\\"), s);
                   // Make sure the "File" you create is a directory!!
                   if (path != null) {
                        System.out.println("");
                        System.out.println("File Found");
                        System.out.print("The File Found at This Path: ");
                        //display the path
                        System.out.print(path);
                   } else {         
                        System.out.println("File Not Found");
         return path;
         private static String recursiveSearch(File f, String name) {  
              // f is the directory to search for the file with name "name"
              File[] childs = f.listFiles();
              Vector dirs = new Vector();
              if (childs != null) {     
                   for (int i = 0 ; i < childs.length ; i++) {       
                        if (childs.isDirectory()) { 
                             // If that is a directory we save it to search later
                             dirs.add(childs[i]);
                        } else { 
                             // Is a regular file
                             if (name.compareTo(childs[i].getName()) == 0) {  
                                  // If the file is what we want we return his path
                                  try {             
                                       return childs[i].getCanonicalPath();
                                  } catch(Exception e) {             
                                       System.err.println("Error getting canonical path\n");
                   for (int i = 0 ; i < dirs.size() ; i++) {       
                        File dirAux = (File)dirs.elementAt(i);
                        String aux = recursiveSearch(dirAux, name);
                        if (aux != null) {  
                             // We have found it inside this directory
                             return aux;
                   // If we get here is because the file is not inside the directory or any subdirectory on it
              return null;
    this code should work if you set it in a class of course ;)

  • [SOLVED] sed; string with file

    Hi,
    Is it possible the to replace a string with file contents, for example; i have the following XML file:
    <?xml version="1.0" encoding="UTF-8"?>
    <modification>
    <id>Testing</id>
    <version>0.0.1</version>
    <vqmver required="true">2.5.0</vqmver>
    <author><![CDATA[Dragon707]]></author>
    <file name="template/a.tpl">
    <operation error="log">
    <search position="before"><![CDATA[
    whooo
    ]]></search>
    <add><![CDATA[
    @include[src/script_whooo.js]
    ]]></add>
    </operation>
    </file>
    <file name="template/b.tpl">
    <operation error="log">
    <search position="before"><![CDATA[
    wheee
    ]]></search>
    <add><![CDATA[
    @include[src/script_wheee.js]
    ]]></add>
    </operation>
    </file>
    </modification>
    And the file src/script_whooo.js contains:
    alert(1);
    And the file src/script_wheee.js contains:
    alert(2);
    What i want is that the string "@include[src/script_whooo.js]" replaces the content with src/script_whooo.js. The expected output is then:
    <?xml version="1.0" encoding="UTF-8"?>
    <modification>
    <id>Testing</id>
    <version>0.0.1</version>
    <vqmver required="true">2.5.0</vqmver>
    <author><![CDATA[Dragon707]]></author>
    <file name="template/a.tpl">
    <operation error="log">
    <search position="before"><![CDATA[
    whooo
    ]]></search>
    <add><![CDATA[
    alert(1);
    ]]></add>
    </operation>
    </file>
    <file name="template/b.tpl">
    <operation error="log">
    <search position="before"><![CDATA[
    wheee
    ]]></search>
    <add><![CDATA[
    alert(2);
    ]]></add>
    </operation>
    </file>
    </modification>
    Last edited by Dragon707 (2014-11-14 12:06:22)

    Procyon wrote:
    I don't think you can get the filename from the file into the 'r' command of sed without naming the filenames explicitly.
    Try this in bash:
    while read; do
    [[ "$REPLY" =~ ^(.*)@include\[([^\]]*)\](.*)$ ]] &&
    REPLY=${BASH_REMATCH[1]}$(cat "${BASH_REMATCH[2]}")${BASH_REMATCH[3]}
    echo "$REPLY"
    done < script.xml
    It only does one @include[] per line though.
    Thanks for your answer, i got it to work however, i still miss the tabs in the output.xml file. Is there a way to keep the tabs in the output.xml?
    #!/bin/bash
    INPUT="input.xml"
    OUTPUT="output.xml"
    echo "" > $OUTPUT
    while read; do
    [[ "$REPLY" =~ ^(.*)@include\[([^\]]*)\](.*)$ ]] &&
    REPLY=${BASH_REMATCH[1]}$(cat "${BASH_REMATCH[2]}")${BASH_REMATCH[3]}
    echo $REPLY >> $OUTPUT
    done < $INPUT

  • Search & Replace function in Files?

    Does there exist a "Search & Replace String" function for Files IO? ...preferable RandomAccessFile.
    Or do I have to make my own parser from scratch.
    Anyone know of free code that exists somewhere? This seems like a function that someone must have made at least or has a use for.
    Thanks for any! :)
    rasmasyean

    The JDeveloper Editor provides Search & Replace functionality for files.
    What I typically do is
    Select menu: Search | Search Source Path...
    Enter Search String and Change Source path
    and other fields and press Start
    Then the Navigator displays a Search tab which lists all files with the matching string.
    Double click on first file in navigator and
    select menu Search | Replace
    In this dialog enter your search, replace, and other options-
    In the Options, If you do not want to be prompted, do not check the Prompt on replace option.
    Select the Scope of Global
    Selectg the Origin of Entire
    When you are ready press the Multiple button to make multiple replacements.
    When you are done with this file,
    Press Ctrl-S to Save the file
    Press Ctrl-F4 to close the window
    Double click on the Next File
    Press Ctrl-R to invoke the Search | Replace dialog.
    You should not need to change any options.
    Press Alt-M to select the Multiple Button!
    While this may seem more complex then a simple Sed / Perl / Python script, it is more controllable, flexible and user friendly.
    Besides, you may learn a few JDeveloper tricks.
    Good Luck,
    -John

  • Working on a script to search for and move files - need Guru help!

    Hi, I'm trying to help my dad with a task and my outdated Applescript knowledge isn't helping me much.
    Here's what I need to do in a nutshell:
    FolderA contains a bunch of JPG files.
    FolderB is the root of a hierarchy of folders containing DNG files.
    Each file of FolderA has a mating file (same name but with .DNG) somewhere in the hierarchy of FolderB.
    The goal is to move each JPG file from Folder A to the folder containing it's mate.
    So, the basic flow is:
    1. Get list of files in folderA
    2. Looping through list, strip out file name (fileA) and find the DNG file somewhere inside FolderB
    3. Get the path of the folder containing the matching DNG file
    4. Copy/move FileA to the folder.
    5. Loop back to #2
    OK, so here's where I am:
    tell application "Finder"
    set JPEGfolder to "Macintosh HD:DadTest1:DadA"
    set DNGfolder to "Macintosh HD:DadTest1:DadB"
    set a_list to every file in Afolder
    repeat with i from 1 to number of items in a_list
    -- Everything happens within this loop
    set a_file to (item i of a_list)
    set fileInfo to info for a_file
    set theName to displayed name of fileInfo as string
    -- now theName contains the actual file name minus the extension
    At this point I don't know how to search for the mating file using Applescript. If I was in UNIX I could do a "find . -name filename" and parse out the path, but I don't know how this works in Applescript.
    I think I can figure out how to move the file once I have the path, but the search routine has me stumped for now.
    Any thoughts?
    Thanks!

    In my opinion your best bet is to take a 180° turn and simplify things significantly.
    Your current approach involves multiple file searches - for each file in the JPEG folder, search all the DNG folders looking for a match. That's an large number of searches, and a large number of something that AppleScript isn't great at.
    Instead you'd be far better off walking once through the DNG folders. For each DNG file look for a matching JPG file in the one folder that contains JPEGs. This would be exponentially faster - one walk through the filesystem vs. one walk through the filesystem for every JPEG.
    This should give you an idea of what I'm talking about (untested):
    global JPEGfolder
    on run
      set JPEGfolder to alias "Macintosh HD:DadTest1:DadA"
      set DNGfolder to alias "Macintosh HD:DadTest1:DadB"
      processAFolder(DNGfolder)
    end run
    on processAFolder(theFolder)
      tell application "Finder"
        repeat with eachItem in folder theFolder
          if class of eachItem is file and name extension of eachItem is "dng" then
            set basename to characters 1 through -5 of (get name of eachItem)
            try
              move file (basename & ".jpg") of folder JPEGfolder to folder theFolder
            end try
          else if class of eachItem is folder then
            my processAFolder(eachItem)
          end if
        end repeat
      end tell
    end processAFolder
    The idea here is that you start off in the top folder and iterate through each item. If the item is a file and it's name extension is DNG then try to move a corresponding file from the JPEG folder to the current folder. This is wrapped in a try block so the script doesn't fail if there is no corresponding JPG.
    If the current item is a folder then the script descends into that folder by calling itself.

  • Searching a string in Forms V5.

    Hi all,
    My requirement is to search a string in a Form (Forms Version 5.0.6.8.0. However If I go to <Filie-Administration-Object list report), I am getting a ascii file. All the objects in the form are listed in the file. So, I do a 'Search' of my required String in the ascii file.
    However, in the <Ascii> file, I find that the program units are not converted to txt file. Only the program unit's name is present.
    Is there any other method, by which I can search my required string in the form(includding all program units, viz., triggers, program units)?
    Thanks in advance for ur help.
    null

    Maybe this will help you:
    We have FREE versions of FormDiff and FormGrep,the productivity tools for Oracle Developer, available for downloading now.
    There are NO FORMS to fill out, NO LIMIT on how long you can use them and best of all NO COST.
    Check out the latest FormDiff features and download your FREE VERSION now: http://www.aug10.com/products/FormDiff
    Using FormDiff, you can now document changes made to Forms and perform meaningful code reviews.
    Checkout the latest FormGrep features and download your FREE VERSION now: http://www.aug10.com/products/FormGrep
    Using FormGrep, you can 'Find and Replace PL/SQL code' across hundreds of FMBs at a time.
    Thank you for your time,
    Jesse Johnson - Managing Principal
    August Tenth Systems, Inc.
    PO Box 3682
    Boulder, CO 80307-3682 http://www.aug10.com/
    Helena

  • RH 11: Search and replace in files: options are grayed out

    Hello to all,
    just wanted to replace a string in my RH Project. Using the Dialog "search and replace in files", the Option "ignore HTML-Tags" is grayed out.
    Even if i create a new, empty Project: the same Problem.
    Is this Option generally not available in RH11 or what is the Trigger to gray the Option out?
    Sorry if I dont hit the English terminology used in RH, I'm using the German Version...
    Regards,
    Julian

    Hi Julian. This sounds like you have the Advanced options displayed. try going back to the Basic options by clicking the double arrow icon in the top right hand corner:

  • Long time to search in 6 GB file using vim editor

    We have RHEL 5.x in our production setup. There is a 6 GB file which I want to inspect to find a certain string but it is not able to find the string as the vim seems to be hanging for more than 1 hr. Please advice how this searching of a string in a big file can be done. I copied the file into a windows system but Microsoft Wordpad or Microsoft Word is failing to open the file. Or, if there is a tool to open large files in Windows as an alternate would also help.
    I hope my query is clear that how to search a string in a big file using vim editor.
    Please revert with the reply to my query.
    Regards

    Much goes on behind the curtain in VIM.  Loading a huge file can be slow because VIM is watching line numbers, doing syntax highlighting, and making a copy of the file for a backup.  Fortunately, this can be turned off; there is even a VIM plugin:
        performance - does vim read the whole file into memory - Stack Overflow
    But using VIM to search large files does not make sense; that is not what the tool was designed to do.  You may as well complain that VIM makes a very poor toothpick.  It is just the wrong tool for the job.  I would use sed(1) or grep(1) to search for the content.  If you need to see some surrounding lines, you can convince grep(1) to do that.  If you need to edit the file content, sed(1) can do that.
    But my real question is: what in the name of sanity produces one gigantic file that needs editing anyway? 

  • ORA-29861 Error while editing or adding search keywords in a File Item

    Hi,
    We are getting the following error while editing or adding search keywords to a file item:
    ORA-29861: domain index is marked LOADING/FAILED/UNUSABLE
    DAD name: portal30 PROCEDURE : PORTAL30.wwv_edit_tab.edititem
    Can you please tell us what went wrong.
    Thanks

    Vikas,
    From the server error messages reference:
    Cause: An attempt has been made to access a domain index that is being built or is marked failed by an unsuccessful ODCIIndexCreate or is marked unusable by a DDL operation.
    Action: Wait if the specified index is marked LOADING Drop the specified index if it is marked FAILED Drop or rebuild the specified index if it is marked UNUSABLE.
    It's possible you were loading the document while the index was being rebuilt. Search all_indexes where DOMIDX_STATUS <> 'VALID' OR DOMIDX_OPSTATUS <> 'VALID' to find the offending index and rebuild it.
    Regards,
    Jerry
    null

  • Always scrolling back to the search bar for pdf files in ibooks. Is there a way to fix this?

    ALWAYS scrolling back up to the search bar for pdf files in ibooks. Is there a way to fix this?

    Care to share your fix with the rest of the community in case anyone else has the same problem or since you found the solution are you off to never be heard from again?

  • Searching for a good file manager

    I'm searching for a good file manager. Konqueror 3.5 is quite good, dolphin 4.1 and konqueror 4.1 are not. Since konqueror 3.5 is going to die due to lack of support in the future, I kind of need to find a new good file manager...
    Do there exist file managers with the following features?
    Many of these features are things I thought were quite logical to be in a file manager, but seem to be missing in most "modern" ones...
    -independent of any desktop (gnome or KDE), just a standalone program
    -preferably not being both a web browser and file manager in once, at least not in an annoying way. Konqueror 3.5 shows that being that combination is possible without being annoying.
    -ability to have a tree view of the folders on one side and list view showing the files and subfolders of the folder currently selected in the tree on the other side
    -detailed list view showing at least filename, type, date and size, and the ability to sort according to any of these properties
    -a non-detailed view showing image contents would also be nice, to browse folders of photos or other images
    -ability to open files in certain programs if you doubleclick the file, NOT open it by singleclicking, singleclicking may only select it
    -ability to select multiple files by dragging box around files or using keys like "ctrl" and "shift"
    -ability to do "open terminal here" or type terminal commands in the current open directory
    -must have ability to drag files from one folder to another, from list view to tree view and vica versa, to move or copy them
    -and must have ability to use "ctrl+c" and "ctrl+v" to copy files and foldes from here to there
    -multiple tabs is a huge plus
    -favorites (to local folder paths) is also a huge plus
    -preview of files when hovering the mouse over them is nice
    -must have ability to zip and unzip (or other compression formats) folders by just right clicking them and choosing a zip/unzip command there
    -in addition to that, must also have ability to browse through a zip file as you would through a normal directory, and drag files from the insides of the zip file to the tree view to automatically unzip those files there, and of course "ctrl+c"/"ctrl+v" should also work to copy a file from the inside of the zip file, to some other folder on your disk
    -no horizontal autoscrolling in the tree view, that is an invention straight from the abyss...

    I know exactly how you feel about KDE 4 vs. 3 -- Konqueror was the best part of KDE for me (pretty much the only part I ever used, actually; my window manager is a slightly modified version of WMII and I generally loathe "desktop environments"). KDE 4 ruined it, completely and utterly.
    I submitted about 20 different bug reports about Konqeuror 4, mostly features that they'd deleted or mangled; some of them are starting to be addressed now. I don't think they'll ever fix the speed issues though, because those are dependent on the underlying KDE 4 libraries as far as I can tell -- it's as if KDE 4 were purposely and deliberately designed to be slower than KDE 3. Even if they fix all of its deficiencies, that'll probably keep me from using it...
    Right now there's KDEmod, which will hopefully maintain its KDE 3 branch for a while longer. It's starting to show some problems, though; I haven't been able to get kdemod konqueror 3 to work fully out of the box (the settings pages are all blank). On my main machine, I somehow managed to hack together some of the KDEmod3 packages so that I have a functional konqueror 3 running alongside the Arch repository's version of KDE4. I'm afraid to pacman -Syu now, though, because it will probably break horribly :P
    I don't remember exactly how I got konqueror 3 going like that, as I did it in my initial fit of rage after I did the pacman -Syu that got me KDE4 (a decision I have regretted ever since), but it was something like this:
    1. move /opt to /opt.kde4
    2. make a new /opt
    3. download several KDE 3 packages from the KDEmod3 repositories manually
    4. extract those packages into the new /opt with tar -xzf (NOT pacman!)
    5. try /opt/kde/bin/konqueror
    6. read reams of error messages about missing libraries, segfaults, etc.
    7. try to supply the missing libraries by downloading other kdemod3 packages and manually extracting them
    8. goto 5
    Then, when everything worked (sort of), I renamed some stuff so that 'konqueror' is konqueror 4 (I think having it konqueror 3 broke something else, but I don't remember what), and konqueror 3 is called 'k3nqueror'.
    If KDEmod3 ever goes away and there's no other good replacement file manager by then, I'll probably take the source code of KDE3 and try to make a standalone version of konqueror out of it. (Which will probably be quite a project because of how interdependent all the KDE components are.)
    Some features I "need" in a file manager, besides the ones you mentioned:
    - Konqueror's tree view (where you can expand folder branches in the file list)
    - Infinite view splitting -- I frequently have my konqueror windows split into 4, sometimes as many as 6 or 7 view panes. Very useful for sorting out files.
    - Selection rectangles are sensitive only over files -- I find full-row-select really annoying, because there are no guaranteed "blank" areas that you can click on to clear a selection. I also use this behaviour to grab long-named files that are interspersed with short ones, because they hilight first when the rectangle touches them (you wouldn't think this very useful, but surprisingly often you do want to do something to all the long-named files...)
    - Right-clicking on a folder and clicking "Paste" pastes into that folder, not the current one -- you'd be amazed at how many file managers get this wrong. I shouldn't have to cd into a folder just to paste some files there.

Maybe you are looking for

  • How do I get a copy of the Mountain Lion OS that I can use to recover?

    How do I make a disc image of my Mac Mini HD that id bootable and has the operating system with all the programs, settings and data.  If I need to replace a defective hard drive it would be good to have an image on a USB flash drive to restore previo

  • Lost all photo stream pics after ios 6 update....

    Hi i lost all my pics from photo stream after ios 6 update and 3 major restores tried everything i can think of but i am very stuck as i only have xp pc wot can i do???? Hope someone is able to help me. Thanks

  • Function module to conver date to internal format

    Can anybody say what is the function module used to convert the format of the date which is taken from excel sheet to the sap format. If so pls tell me how to use that function module.

  • Excise Invoice (J1IS)

    Dear Friends, System allowing us to create multiple Excise Invoice T. Code (J1IS) for one Material Documents. Please let me know how to control of multiple excise invoices for one material document. Please reply as soon as possible & Thanks in advanc

  • PSE 12

    I tried to install PSE 12 as an upgrade to PSE 9 on a Win 7 netbook (50+ GB diskspace available). The installation stops at about 95% without an error-message, de-installation didn't work too. So I deleted all PSE 12-files I could find manually and t