Search for a String in a list of files
Could anyone please send me a java sample code which searches for a string from a list of files and returns me the filename and the line in which the Search String was found ?
Thanks in advance
RR
Simple solution would be -
1. Traverse a directory for each file.
2. Read each file using Buffered Reader.
3. Use readLine() method to read a line.
4. Use String.indexOf to see if the data which you are looking for is there in the line or not.
5. If its there then store the line number and file name.
6. When the loop will end you will have list of file name and line number where the data which you are looking for is present.
Similar Messages
-
How to search for a string in ALL Function Modules source code
Hello,
I want to search for the string "HELLO" in all FUNCTION MODULES source code(FM, no reports/programs).
Is this possible? How?
Cheers,
Andyhi,
Execute RPR_ABAP_SOURCE_SCAN to search for a string in the code ... Press where-used-list button on the program which takes to the function group or the function module where it is used ..
Regards,
Santosh -
How can I search for a string like a partial IP address in the global search
When searching for a string like "10.255." the global search finds messages containing "255" or "10" and both.
This happens no matter whether quotation is used or not.
When quotation is used it probably will match on the given order as well, but beeing in the timezone '+0100' the string "10" is always found first (in the email headers...).
Is there a way to tell the global search not to use '.' or any other character as whitespace?When searching for a string like "10.255." the global search finds messages containing "255" or "10" and both.
This happens no matter whether quotation is used or not.
When quotation is used it probably will match on the given order as well, but beeing in the timezone '+0100' the string "10" is always found first (in the email headers...).
Is there a way to tell the global search not to use '.' or any other character as whitespace? -
How do i search for a string in a txt file using java??
How do i search for a string in a txt file using java??
could you please help thanks
JRegular expressinos work just fine, especially when
searching for patterns. But they seem to be impying
it's a specific group of characters they're looking
for, and indexOf() is much faster than a regex.If he's reading from a file, the I/O time will likely swamp any performance hit that regex introduces. I think contains() (or indexOf() if he's not on 5.0 yet) is preferable to regex just because it's simpler. (And in the case of contains(), the name makes for a very clear, direct mapping between your intent and the code that realizes it.) -
Searching for a string in an excel file and return true if found.
How can I search for a string in an excel file and return true if found, its location and also a value.
The problem with searching an excel file is that it contains a header. It would be easiest if you just read the file into a LabVIEW array and search the array. This way you can also get the index and the value of the location.
-
Search for a String within a document (Word, txt, doc) using JSP, JAVA
Hi
I have created a little application that uses combination of JSP and HTML. Users of this application can upload documents which are then stored on the server. I need to develop functionality where I can allows users to search for a string within a document. More precisely, user would type in some string in a text box and application will search all uploaded documents for that string and return the downloadable links to those documents that contains that string. I have never done this before. I was wondering if someone could get me started on this or point me to some thread where this idea is already discussed. Any Jave code exists for searching through documents??
Thanks for your help
Rizhttp://www.ibm.com/developerworks/java/library/j-text-searching.html
http://en.wikipedia.org/wiki/Full_text_search
Type these parameter in yahoo:+efficient text search
you will need something like openoffice library to read microsoft word document. -
Search for a string in SAP Script
Hello Experts,
Is there a way to search for a string in all Z SAP scripts, like ABAP source scan?
Regards,
Hari.Try using function module "READ_FORM" (you will have to write a simple z-program to find all SAPscripts in your system then use this function module to search the SAPScript Forms for a particular string).
All you have to do is supply the "FORM" name and it will return all of the Pages, Paragraphs, and Texts etc....
More specifically, try looping at the "FORM_LINES" internal table result and you will see the SAPScript text there....
Have fun !
Edited by: Christopher Twirbutt on Sep 16, 2009 12:43 AM -
Is Safari Find function flexible? (Search for inner strings of characters?)
I'm running 10.6.8 with Safari Version 5.1.7 (6534.57.2). I see that when you search a web page using the Safari Find function, you can only search for the beginnings of words, not for character strings within the words. Is it possible to expand the Find function's capability to search for inner strings of characters?
use command F or the edit menus to make the page search box visible - click the magnify/arrow icon at the left side of it - choose "contains" or "starts with".
-
How to continously read for a string or word in a file?
Hi
I have been trying for a while now to search for a word that is being written to a file.
I was wondering if anyone can get me over this hump?
What I am doing is reading from the serial port to a file (example file called test), and while this is being done I want to search for the word "passed" or the phrase "test passed"
Once I fine this word or phrase, I can stop the test
I cannot figure out how to search the file, I used the scan file VI and the search/ replace VI etc with no luck!
Your suggestions is appreciatedIt's always best to post your code so others can see the work you've done. Suggestions will be more effective that way.
So your reading from a serial port to a file? What do you mean by this? Are you reading from the serial port and writing the data to a file? It's the file you want to read, isn't it? If I had your code I could answer my own questions
Why don't you just monitor the incoming data stream from the serial port for "passed."
But to read from a file and search for a string, Smercurio is correct. Match Pattern will do what you need (You can use this same function for ASCII serial data as well).
Reese, (former CLAD, future CLD)
Some people call me the Space Cowboy!
Some call me the gangster of love.
Some people call me MoReese!
...I'm right here baby, right here, right here, right here at home -
Searching for a word or phrase in a file on NSS Pool/Volume
I have encountered a strange issue in that if I search for a word or phrase in a file at any level of the volume, from the root, down to sub folders, I get different results from 2 or more PC's.
Workstations are all Win XP SP2, Novell Client 4.91 SP4 for Windows
Server NW 6.5 SP6 with all post SP's installed.
I have ran a nss /PoolRebuild=POOLNAME and a NSS /VisibilityRebuild=VOLNAME
There is only one volume on this pool.
And I still encounter the same results.
As one example:
On my Admin workstation When I search the top level Folder of Closed Client folders for the word chronology, I get 2 files returned named chronfile1 and chonfile2, when I search from any other workstation (I have tried 4 different workstations at this point) at the same folder level, for the same word Chronology, I get multiple files with the Word in the File, but I do not see files chronfile1 or chronfile2. Likewise, the file names returned form the search results on the other workstations, are not returned in the search list ran on the admin (Mine) workstation. And yes, I am logged in as admin on the other workstations when running the search.
So far, this issue is only appearing on 1 volume.
Thoughts?Originally Posted by ataubman
If you log in to the second PC as Admin, does the symptom move? IOW does it follow the user or the workstation? If the user you may have some odd file system rights set, although your specific results you report are puzzling.
I'm assuming you are using the Windows desktop search tool?
I ran a NSS /PoolRebuild last night which fixed an issue the workstations not being able to see the 2 files in question.
Previous night I had just performed an NSS /PoolVerify.
Part of the other anomoly, the other workstations seeing more files than the admin workstation (I feel so Stupid, after 25 years you think I'd be able to spot the obvious) the reason the other workstations were returning files that the Admin workstation was not - Admin workstation doesn't have Word Perfect installed.
Somebody, give me a Gibbs head slap, now! -
Search for "A word or phrase in the file" in .trc files gives no result
Hi
When i Search through Explorer using search for "A word or phrase in the file" in .trc files I get no result.
Probably because these files are of type "Microsoft Network Monitor Document".
But I can open them using Notepad, so why can't I search for a word in these files?
I there another way to search?
Normally I ofcourse use Visual Admin. but there are a lot of trace files so it would be nice to do this kind of search
br PeterHi Peter,
This is a known problem, see http://support.microsoft.com/kb/309173
An alternative is to use other tools which search even faster than the slow MS search does.
Hope it helps
Detlev -
I have been searching high and low for this one. I have a vbscript that can successfully perform the function if one file is listed. It does a Wscript.echo on the results and if I run this via command using cscript, I can output to a text file
that way. However, I cannot seem to get it to work properly if I want it to search ALL the files in the folder. At one point, I was able to have it create the output file and appear as if it worked, but it never showed any results when the script
was executed and folder was scanned. So I am going back to the drawing board and starting from the beginning.
I also have a txt file that contains the list of string text entries I would like it to search for. Just for testing, I placed 4 lines of sample text and one single matching text in various target files and nothing comes back. The current script
I use for each file has been executed with a few hundred string text lines I want it to search against to well over one thousand. It might take awhile, but it works every time. The purpose is to let this run against various log files in a folder and
let it search. There is no deleting, moving, changing of either the target folder/files to run against, nor of the file that contains the strings to search for. It is a search (read) only function, going thru the entire contents of the folder and
when done, performs the loop function and onto the next file to repeat the process until all files are searched. When completed, instead of running a cscript to execute the script and outputting the results to text, I am trying to create that as part
of the overall script. Saving yet another step for me to do.
My current script is set to append to the same results file and will echo [name of file I am searching]: No errors found. Otherwise, the
output shows the filename and the string text that matched. Because the results append to it, I can only run the script against each file separately or create individual output names. I would rather not do that if I could include it all in one.
This would also free me from babysitting it and running each file script separately upon the other's completion. I can continue with my job and come back later and view the completed report all in one. So
if I could perform this on an entire folder, then I would want the entries to include the filename, the line number that the match occurred on in that file and the string text that was matched (each occurrence). I don't want the entire line to be listed
where the error was, just the match itself.
Example: (In the event this doesn't display correctly below, each match, it's corresponding filename and line number all go together on the same line. It somehow posted the example jumbled when I listed it)
File1.txt Line 54
Job terminated unexpectedly
File1.txt Line 58 Process not completed
File1.txt
Line 101 User input not provided
File1.txt
Line 105 Process not completed
File2.txt
No errors found
File3.txt
Line 35 No tape media found
File3.txt
Line 156 Bad surface media
File3.txt Line 188
Process terminated
Those are just random fake examples for this post.
This allows me to perform analysis on a set of files for various projects I am doing. Later on, when the entire search is completed, I can go back to the results file and look and see what files had items I wish to follow up on. Therefore, the
line number that each match was found on will allow me to see the big picture of what was going on when the entry was logged.
I actually import the results file into a spreadsheet, where further information is stored regarding each individual text string I am using. Very useful.
If you know how I can successfully achieve this in one script, please share. I have seen plenty of posts out there where people have requested all different aspects of it, but I have yet to see it all put together in one and work successfully.
Thanks for helping.I'm sorry. I was so consumed in locating the issue that I completely overlooked posting what exactly I was needing help with. I did have one created, but I came across one that seemed more organized than what I originally created. Later
on I would learn that I had an error in log location on my original script and therefore thought it wasn't working properly. Now that I am thinking that I am pretty close to achieving what I want with this one, I am just going to stick with it.
However, I could still use help on it. I am not sure what I did not set correctly or perhaps overlooking as a typing error that my very last line of this throws an "Expected Statement" error. If I end with End, then it still gives same
results.
So to give credit where I located this:
http://vbscriptwmi.uw.hu/ch12lev1sec7.html
I then adjusted it for what I was doing.
What this does does is it searches thru log files in a directory you specify when prompted. It looks for words that are contained in another file; objFile2, and outputs the results of all matching words in each of those log files to another file: errors.log
Once all files are scanned to the end, the objects are closed and then a message is echoed letting you know (whether there errors found or not), so you know the script has been completed.
What I had hoped to achieve was an output to the errors.log (when matches were found) the file name, the line number that match was located on in that file and what was the actual string text (not the whole line) that matched. That way, I can go directly
to each instance for particular events if further analysis is needed later on.
So I could use help on what statement should I be closing this with. What event, events or error did I overlook that I keep getting prompted for that. Any help would be appreciated.
Option Explicit
'Prompt user for the log file they want to search
Dim varLogPath
varLogPath = InputBox("Enter the complete path of the logs folder.")
'Create filesystem object
Dim oFSO
Set oFSO = WScript.CreateObject("Scripting.FileSystemObject")
'Creates the output file that will contain errors found during search
Dim oTSOut
Set oTSOut = oFSO.CreateTextFile("c:\Scripts\errors.log")
'Loop through each file in the folder
Dim oFile, varFoundNone
VarFoundNone = True
For Each oFile In oFSO.GetFolder(varLogPath).Files
'Verifies files scanned are log files
If LCase(Right(oFile.Name,3)) = "log" Then
'Open the log file
Dim oTS
oTS = oFSO.OpenTextFile(oFile.Path)
'Sets the file log that contains error list to look for
Dim oFile2
Set oFile2 = oFSO.OpenTextFile("c:\Scripts\livescan\lserrors.txt", ForReading)
'Begin reading each line of the textstream
Dim varLine
Do Until oTS.AtEndOfStream
varLine = oTS.ReadLine
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
Dim colMatches, strName, strText
Do Until oErrors.AtEndOfStream
strName = oFile2.ReadLine
objRegEx.Pattern = ".{0,}" & strName & ".{0,}\n"
Set colMatches = objRegEx.Execute(varLine)
If colMatches.Count > 0 Then
For Each strMatch in colMatches
strText = strText & strMatch.Value
WScript.Echo "Errors found."
oTSOut.WriteLine oFile.Name, varLine.Line, varLine
VarFoundNone = False
Next
End If
Loop
oTS.Close
oFile2.Close
oTSOut.Close
Exit Do
If VarFoundNone = True Then
WScript.Echo "No errors found."
Else
WScript.Echo "Errors found. Check logfile for more info."
End If
End if -
Help to search for a string value and return the index in the arraylist
Hello,
I just start java programming for the last three weeks and I cannot find a solution for this problem. I have the following List with string and integer value as shown below:
List<Empl> list= new ArrayList<Empl>();
list.add(new Empl(1,"Jim", "Balu",88);
list.add(new Empl(3,"Bob", "Howards",2);
list.add(new Empl(2,"Chris", "Hup",8);
I have no problem of sorting this arraylist either by firstname or lastname. However, I cannot think of a way to search for a firstname or lastname and returing the whole row. I do not want to use index since I am asking user to enter the name to search. Here is my code to search for an empl based on index.
System.out.print("Please enter index to search or (q)uit: ");
String ans = sc.next();
System.out.println();
int ians = Integer(ans);
if (ans.equalsIgnoreCase("q"))
choice = "n";
else
System.out.println("index " + list.get(ians)); //this will print out the whole row based on the index
Since the user will never seen the contents of the arraylist, is there a way that I can search by string last/first name and will get the index location in int if the result is met?
Please advice and thank you.
Bob.user11191663 wrote:
Since the user will never seen the contents of the arraylist, is there a way that I can search by string last/first name and will get the index location in int if the result is met?Another possibility is to set up an ArrayList for each thing you want to search on and then every time you add an employee, add the piece of data you want as well, viz:
Empl e = new Empl(1,"Jim", "Balu",88);
list.add(e);
firstNames.add(e.firstName());As long as you always add them in the same order, the indexes will match, so you could do something like
ians = firstNames.indexOf(nameToFind);to return the index of the name, if it's there (if not, it will return -1).
I wouldn't recommend this as standard practise, but it should be OK for the level you're at.
NOTE: indexOf() returns the index of the FIRST matching item. You may want to think about what you want to do if there are more than 1.
Winston -
How to search for particular string in array?
I am struggling to figure out how to search array contents for a string and then delete the entry from the array if it is found.
The code for a program that allows the user to enter up to 20 inventory items (tools) is posted below; I apologize in advance for it as I am also not having much success grasping the concept of OOP and I am certain it is does not conform although it all compiles.
Anyway, if you can provide some assistance as to how to go about searching the array I would be most grateful. Many thanks in advance..
// ==========================================================
// Tool class
// Reads user input from keyboard and writes to text file a list of entered
// inventory items (tools)
// ==========================================================
import java.io.*;
import java.text.DecimalFormat;
public class Tool
private String name;
private double totalCost;
int units;
// int record;
double price;
// Constructor for Tool
public Tool(String toolName, int unitQty, double costPrice)
name = toolName;
units = unitQty;
price = costPrice;
public static void main( String args[] ) throws Exception
String file = "test.txt";
String input;
String item;
String addItem;
int choice = 0;
int recordNum = 1;
int qty;
double price;
boolean valid;
String toolName = "";
String itemQty = "";
String itemCost = "";
DecimalFormat fmt = new DecimalFormat("##0.00");
// Display menu options
System.out.println();
System.out.println(" 1. ENTER item(s) into inventory");
System.out.println(" 2. DELETE item(s) from inventory");
System.out.println(" 3. DISPLAY item(s) in inventory");
System.out.println();
System.out.println(" 9. QUIT program");
System.out.println();
System.out.println("==================================================");
System.out.println();
// Declare and initialize keyboard input stream
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
do
valid = false;
try
System.out.print(" Enter an option > ");
input = stdin.readLine();
choice = Integer.parseInt(input);
System.out.println();
valid = true;
catch(NumberFormatException exception)
System.out.println();
System.out.println(" Only numbers accepted. Try again.");
while (!valid);
while (choice != 1 && choice != 2 && choice != 9)
System.out.println(" Not a valid option. Try again.");
System.out.print(" Enter an option > ");
input = stdin.readLine();
choice = Integer.parseInt(input);
System.out.println();
if (choice == 1)
// Declare and initialize input file
FileWriter fileName = new FileWriter(file);
BufferedWriter bufferedWriter = new BufferedWriter(fileName);
PrintWriter dataFile = new PrintWriter(bufferedWriter);
do
addItem="Y";
System.out.print(" Enter item #" + recordNum + " name > ");
toolName = stdin.readLine();
if (toolName.length() > 15)
toolName = toolName.substring(0,15); // Convert to uppercase
toolName = toolName.toUpperCase();
dataFile.print (toolName + "\t");
do
valid = false;
try
// Prompt for item quantity
System.out.print(" Enter item #" + recordNum + " quantity > ");
itemQty = stdin.readLine();
// Parse integer as string
qty = Integer.parseInt (itemQty);
// Write item quantity to data file
dataFile.print(itemQty + "\t");
valid=true;
catch(NumberFormatException exception)
// Throw error for all non-integer input
System.out.println();
System.out.println(" Only whole numbers please. Try again.");
while (!valid);
do
valid = false;
try
// Prompt for item cost
System.out.print(" Enter item #" + recordNum + " cost (A$) > ");
itemCost = stdin.readLine();
// Parse float as string
price = Double.parseDouble(itemCost);
// Write item cost to data file
dataFile.println(fmt.format(price));
valid = true;
catch(NumberFormatException exception)
// Throw error for all non-number input (integers
// allowed)
System.out.println();
System.out.println(" Only numbers please. Try again.");
while (!valid);
// Prompt to add another item
System.out.println();
System.out.print(" Add another item? Y/N > ");
addItem = stdin.readLine();
while ((!addItem.equalsIgnoreCase("Y")) && (!addItem.equalsIgnoreCase("N")))
// Prompt for valid input if not Y or N
System.out.println();
System.out.println(" Not a valid option. Try again.");
System.out.print(" Add another item? Y/N > ");
addItem = stdin.readLine();
System.out.println();
// Increment record number by 1
recordNum++;
if (addItem.equalsIgnoreCase("N"))
System.out.println();
System.out.println(" The output file \"" + file + "\" has been saved.");
System.out.println();
System.out.println(" Quitting program.");
while (addItem.equalsIgnoreCase("Y"));
// Close input file
dataFile.close();
if (choice == 2)
try {
Read user input (array search string)
Search array
If match found, remove entry from array
Confirm "deletion" and display new array contents
catch block {
} // class
// ==========================================================
// ListToolDetails class
// Reads a text file into an array and displays contents as an inventory list
// ==========================================================
import java.io.*;
import java.util.StringTokenizer;
import java.text.DecimalFormat;
public class ListToolDetails {
// Declare variable
private Tool[] toolArray; // Reference to an array of objects of type Tool
private int toolCount;
public static void main(String args[]) throws Exception {
String line, name, file = "test.txt";
int units, count = 0, record = 1;
double price, total = 0;
DecimalFormat fmt = new DecimalFormat("##0.00");
final int MAX = 20;
Tool[] items = new Tool[MAX];
System.out.println("Inventory List");
System.out.println();
System.out.println("REC.#" + "\t" + "ITEM" + "\t" + "QTY" + "\t"
+ "PRICE" + "\t" + "TOTAL");
System.out.println("\t" + "\t" + "\t" + "\t" + "PRICE");
System.out.println();
try {
// Read a tab-delimited text file of inventory items
FileReader fr = new FileReader(file);
BufferedReader inFile = new BufferedReader(fr);
StringTokenizer tokenizer;
while ((line = inFile.readLine()) != null) {
tokenizer = new StringTokenizer(line, "\t");
name = tokenizer.nextToken();
try {
units = Integer.parseInt(tokenizer.nextToken());
price = Double.parseDouble(tokenizer.nextToken());
items[count++] = new Tool(name, units, price);
total = units * price;
} catch (NumberFormatException exception) {
System.out.println("Error in input. Line ignored:");
System.out.println(line);
System.out.print(" " + count + "\t");
System.out.print(line + "\t");
System.out.print(fmt.format(total));
System.out.println();
inFile.close();
} catch (FileNotFoundException exception) {
System.out.println("The file " + file + " was not found.");
} catch (IOException exception) {
System.out.println(exception);
System.out.println();
// Unfinished functionality for displaying "error" message if user tries to
// add more than 20 tools to inventory
public void addTool(Tool maxtools) {
if (toolCount < toolArray.length) {
toolArray[toolCount] = maxtools;
toolCount += 1;
} else {
System.out.print("Inventory is full. Cannot add new tools.");
// This should search inventory by string and remove/overwrite matching
// entry with null
public Tool getTool(int index) {
if (index < toolCount) {
return toolArray[index];
} else {
System.out
.println("That tool does not exist at this index location.");
return null;
} // classData file contents:
TOOL 1 1 1.21
TOOL 2 8 3.85
TOOL 3 35 6.92Ok, so you have an array of Strings. And if the string you are searching for is in the array, you need to remove it from the array.
Is that right?
Can you use an ArrayList<String> instead of a String[ ]?
To find it, you would just do:
for (String item : myArray){
if (item.equals(searchString){
// remove the element. Not trivial for arrays, very easy for ArrayList
}Heck, with an arraylist you might be able to do the following:
arrayList.remove(arrayList.indexOf(searchString));[edit]
the above assumes you are using 1.5
uses generics and for each loop
[edit2]
and kinda won't work it you have to use an array since you will need the array index to be able to remove it. See the previous post for that, then set the value in that array index to null.
Message was edited by:
BaltimoreJohn -
Hi All,
My requirement is to search string Like "List Price",if the input field is having this string at any place i need to transfer input value to target.
Could any one help me on this writing a UDF for this.
Input : Final List Price Vendor
check for :List Price
then pass the other values to Target.
Thanks,
MadhuHi,
Check with this UDF
public String Search(String a,String b,Container container)
String c;
int i;
i = a.indexOf(b);
if(i == -1)
c = " ";
else
c = a;
return c;
Here a is the input and b is the search string.
0r
if the value of search string doesnt change dynamically then the UDF can be like this
public String Search(String a,Container container)
String c;
String b;
b = "List price"
int i;
i = a.indexOf(b);
if(i == -1)
c = " ";
else
c = a;
return c;
Edited by: malini balasubramaniam on Aug 5, 2008 9:15 AM
Maybe you are looking for
-
How to create a custom protectdoublesubmit window?
Hi , I am using the xhtmlb:protectdoublesubmit in one BSP page as follows: <xhtmlb:protectDoubleSubmit timer = "400" active = "TRUE" design = "POPUP"
-
BAPI for creation of Authorization Objects in BI 7.0
Hi BW Gurus, Greetings!!! Is there any BAPI Available for creation of Authorization Objects in BI 7.0. The data will be transferred through flatfiles. Kindly provide me the info as earliest as possible. Best Regards, Priya
-
''dupe of https://support.mozilla.com/en-US/questions/907431'' I can't email any document that has within it an image that is a jpeg, pdf, etc.
-
Hi Guys, I'm looking for a sound like the one that is in the end of I'm Outta Time by Oasis, like a clock, there any similar in mainstage? Thanks, Bye
-
Hi! I know flash has seek bar component for flv videos but I'm streaming music from net. I have a code for loading entire song but is it possible to add a seek bar to show what part of song is playing