Help with searching and replacing

This kind of carries on from the previous topic i posted, but that one came to a bit of a dead end. Here is the code that i have so far:
import java.io.*;
import java.util.*;
class SearchReplaceApp
     public static InputStreamReader input =
     new InputStreamReader(System.in);
     public static BufferedReader keyboardInput =
     new BufferedReader(input);
     public static void main(String[] args) throws IOException
     FileReader file = new FileReader(args[0]);
     BufferedReader MyFile = new BufferedReader(file);
          StringTokenizer TokenizeMe;
          int NumberOfTokens = 0;
          int NumberOfWords = 0;
     TokenizeMe = new StringTokenizer(MyFile.readLine());
     NumberOfTokens = TokenizeMe.countTokens();
     while (NumberOfTokens != 0)
          for (int WordsInLine=1; WordsInLine<=NumberOfTokens;
                    WordsInLine++)
               System.out.print(TokenizeMe.nextToken()+" ");
          System.out.println();
          NumberOfWords += NumberOfTokens;
          String line = MyFile.readLine();
          if (line==null) break;
          TokenizeMe = new StringTokenizer(line);
          NumberOfTokens = TokenizeMe.countTokens();
          String findWord;
          String replaceWord;
          System.out.println ("Search for?:");
          findWord = keyboardInput.readLine();
          System.out.println("Replace With?:");
          replaceWord = keyboardInput.readLine();
          if (line.equals(findWord)) {               
          line = replaceWord;
     System.out.println("\nThis file contains " + NumberOfWords + " words");
     MyFile.close();
     }The problem is that it asks to search for a word after it has read each line of the file to the screen, instead of just asking when it has read in the whole file, which is what i want it to do. can anyone help me with this?
I think the problem lies in the part :
          String findWord;
          String replaceWord;
          System.out.println ("Search for?:");
          findWord = keyboardInput.readLine();
          System.out.println("Replace With?:");
          replaceWord = keyboardInput.readLine();
          if (line.equals(findWord)) {               
          line = replaceWord;
I would also like the program to display the dedited text after the replace has been completed e.g.
java SearchReplaceApp test.txt
This is a test
This is a test
This is a Test
This is a Test
This file contains 16 words
Search for?: test
Replace with?: Test
This is a Test
This is a Test
This is a Test
This is a Test
Search for?:
etc............................
Any help at all would be appreaciated as im getting a bit frustated with this program and also my own lack of knowledge.
Thanks
Max

Hi,
sorri for that code which sent. here's is the correct code
import java.io.*;
import java.util.*;
class SearchReplaceApp
public static InputStreamReader input = new InputStreamReader(System.in);
public static BufferedReader keyboardInput = new BufferedReader(input);
public static void main(String[] args) throws IOException
FileReader file = new FileReader(args[0]);
BufferedReader MyFile = new BufferedReader(file);
StringTokenizer TokenizeMe;
int NumberOfTokens = 0;
int NumberOfWords = 0;
String line = MyFile.readLine();
String completeText = "";
Vector strVec = new Vector();
while(line!=null)
completeText+="\r\n";
StringTokenizer tokenizeLine = new StringTokenizer(line);
NumberOfWords+=tokenizeLine.countTokens();
completeText +=line;strVec.add(line);
line = MyFile.readLine();
MyFile.close();
System.out.println(completeText);
System.out.println("This file contains"+NumberOfWords+ "words");
String findWord="";
String replaceWord;
String resultStr = "\r\n";
for ( ;;)
System.out.println ("Search for?:");
System.out.println("Please enter quit for quit:");
findWord = keyboardInput.readLine();
if(findWord.equals("quit")) break;
//While findWord is not =null do.......
System.out.println("Replace With?:");
replaceWord = keyboardInput.readLine();
for(int i=0;i<strVec.size();i++)
String str = (String)strVec.get(i);
TokenizeMe = new StringTokenizer(str);
while ( TokenizeMe.hasMoreTokens())
String token = TokenizeMe.nextToken();
if (token.trim().equals(findWord.trim()))
token = replaceWord; resultStr+=" " +token;
else{resultStr+=" "+token;}}resultStr+="\r\n";
System.out.println("COMPLETE TEXT AFTER REPLACE IS "+resultStr);
//Save changes back to original file
String str = resultStr;
FileWriter newFile = new FileWriter(args[0]);
PrintWriter fw = new PrintWriter(newFile);
char[] ch = new char[str.length()];
str.getChars(0,str.length(),ch,0);
fw.write(ch);
fw.flush();
fw.close();
hope this solves your problem.
shyam

Similar Messages

  • Help with search and replace script please

    Hi all
    I've written a javascript which uses various GREP and text find/changes to copy some text from the first two paragraphs of a document and use them elsewhere (in the running head and footers) and now I want to delete the first two paragraphs. Not sure how I would do that. If I was doing a manual find/change (with nothing selected) it would automatically select the first para in the first text box but when I run teh following;
    app.findGrepPreferences.findWhat = "^.+$";
    app.changeGrepPreferences.changeTo="";
    app.activeDocument.changeGrep();
    it finds all paragraphs and deletes them. I was going to include the code twice; once to delete the first paragraph and then again to delete the other (new first) paragraph. My JS skills are shaky but I'm quite comfortable with GREP. Can anyone point me in the right direction for how I acheive what I want? If I did a for loop surely I'd just be doing the same thing but more than once!
    Much to my surprise the rest of the script is working although it made my brain hurt!
    thanks for any suggestions,
    Iain

    Oooh. After
    myStory=app.activeDocument.stories.everyItem();
    the variable "myStory" won't point to just a single story, but ... to "every story". So that's why the next line removes more than you intended!
    What the "everyItem" thingy internally does is still unclear to me, but that doesn't keep me from using it -- but only when you absolutely, positively want to perform an action on every item
    Now the usual examples say something like
    myStory = app.activeDocument.stories.item(0); // access first story
    but that's No Good. Even if your first story is the one you are targeting today, tomorrow, in a different document, it'll be story #1, or #5, or #255. There is no general rule that states the first story is always the largest one, or something like that.
    If this is going to be used with a document template, the best way to identify the target story is by giving the first text frame a unique label. Otherwise, you'll have to think of something else ... A couple of other strategies:
    1. You are already using GREP to find stuff. If one of those searches is guaranteed to return just text in the one story you are interested in, you can use this.
    2. You mention headers and footers. If your main text is the only one that runs through multiple text frames, you can loop over all stories and check which one runs through than a single text frame.
    3. ... (I'm pretty sure there are some more strategies ...)

  • Problem with search and replace

    I'm workin on Windows XP, Dreamwearver 8
    When I do a search and replace in a site, the changes will be
    made correctly, however, the auto date stamp that I'm using on my
    pages will duplicate on random pages and overwrite text This
    doesn't occur on all pages, and isn't connected with the actual
    change I'm making. Has anyone experienced this?

    Ok Gary, but...
    in a SQLWorksheet write:
    ababab
    Now Edit -> Replace search for b , replace with \nb
    Result (the last b is not replaced):
    a
    ba
    bab
    At this point, I want to have my string back on one line: Edit -> Replace search for \n , replace with (nothing here)
    Result: The search text "\n" was not found.
    And to make it work I have to tick the Regular Expressions checkbox (in this case substitute escaped characters is ignored).
    While I agree that "it is good to have a choice", I personally find it confusing: none of the few text editors I use (Linux or OSX) behaves this way.
    Regards.
    Alessandro

  • Need Help With find and Replace

    I am a little green to this all. I am trying to find and
    replace a word inside the edit region and Dreamweaver will not
    change it, because it says its inside a locked region, but its a
    editable region?
    I have about 900 pages I need to make this change on and was
    relying on the find and replace tool to do that. I tried differn't
    advanced options, nothing seams to change it. I am using cs3.
    Thanks for any help

    Using Templates with a 900 page site is a crime against
    humanity. You reach
    the optimal size for Templates between about 50 and 100.
    The error you are getting suggests that there are coding
    errors on the page
    (perhaps even unrelated to ANY DW Template markup). We'd need
    to see the
    page to make progress with what that might be, as Alan says.
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================
    "RyanWaters" <[email protected]> wrote in
    message
    news:ggs7fq$gnq$[email protected]..
    >I am a little green to this all. I am trying to find and
    replace a word
    >inside
    > the edit region and Dreamweaver will not change it,
    because it says its
    > inside
    > a locked region, but its a editable region?
    > I have about 900 pages I need to make this change on and
    was relying on
    > the
    > find and replace tool to do that. I tried differn't
    advanced options,
    > nothing
    > seams to change it. I am using cs3. Thanks for any help
    >

  • Help with find and replace regex

    Hello.
    I have a page listing about 50 services that have named
    anchors to a
    glossary page. Something like this:
    <a href="/glossary.html#Blogging">Blogging</a>
    And what I need is to have the glossary open in a new window.
    So how
    do I write a regex that will give me:
    <a href="/glossary.html#Blogging"
    taget="blank">Blogging</a>
    Thanks for any help
    Lance

    Thanks Brendon.
    It's Regular Expression; an optioin in the find and replace
    dialog.
    I've got to replace 50 of these anchors, each different.
    <a href="/glossary.html#Blogging">Blogging</a>
    <a href="/glossary.html#yadayada">yadayada</a>
    etc.
    to make them each open in a new window.
    <a href="/glossary.html#Blogging"
    taget="blank">Blogging</a>
    L.
    On Thu, 18 Oct 2007 14:40:46 +1300, "Brendon"
    <[email protected]>
    wrote:
    >Whats a regex?
    >Why not just do a Find and Replace? Specify the current
    local site, and
    >voila. Make sure you spell target correctly though ;-)
    >
    >
    ><@networkologist@@gmail.com> wrote in message
    >news:[email protected]..
    >> Hello.
    >>
    >> I have a page listing about 50 services that have
    named anchors to a
    >> glossary page. Something like this:
    >>
    >> <a
    href="/glossary.html#Blogging">Blogging</a>
    >>
    >> And what I need is to have the glossary open in a
    new window. So how
    >> do I write a regex that will give me:
    >>
    >> <a href="/glossary.html#Blogging"
    taget="blank">Blogging</a>
    >>
    >> Thanks for any help
    >>
    >>
    >>
    >> Lance
    >

  • Search and replace with comma

    Hello All,
    I want some help. Please help me.
    I have comma delimited Data. When I’m converting Sting to Array, If two commas exists in between then its displaying “Zero” (because its array propriety ). Instead of that I want to display “NaN” .
    Please give me any idea to replace comma to NaN. I tried with Search and Replace but it’s not giving as I expected.
    Munna
    Solved!
    Go to Solution.

    Hello GerdW,
    Thanks you so much for your reply.
    I thought, instead of replacing trailing comma by NaN adding comma before string is more better (because to many string manipulations) But, it’s taking more execution time.
    Munna
    Attachments:
    Search and Replace.vi ‏415 KB

  • Search and replace string problems

    Hi to all,
    I have problem with Search and replace string function. It shows me a wrong Value (Number) from 15 to 100 is everything OK (15=0, 30=1, 45=2, 100=3), but after 100 ........
    Take look in VI and if you have any ideas post them please
    THX
    Igor 
    Attachments:
    indexing.vi ‏10 KB

    there will be no 15115 string, but 15 or 115 and 15 is 0, 115 is 4. Anyway, i have changed string input format and now its working THX for your help
    Attachments:
    indexing.vi ‏10 KB

  • Search and Replace on master pages

    Is there a way to do Search and Replace on masterpages.
    Example: There are 30 files in a .book document.
    On those 20 files the header and footer must change.
    The header and footer are on the master pages.
    Can you p. e. change "Haeder1" to "Header1" with Search and Replace?
    Right now we do it on this way:
    Open all files in book
    Set view to Masterpage manually file per file (30 times).
    Search "Haeder1" and replace with "Header1" (option search in book)
    Is there a way to do it faster?
    Thanks in advance
    Sander Gheldof

    Thanks for your help...but the headers aren't variables...
    It may be that your solution is to bite the bullet today and do the page-by-page change of your headers to variables.
    System header variables can, for example, contain text from a paragraph style such as a level-[ 1 | 2 | 3...] heading. Or other values received from a FrameMaker named paragraph style.
    User-defined variables can also be used in headers and footers, although they can't be made to do the zippy automatic things system header/footer variables do...
    The essential point being that after doing it the hard way today, you may never need to do it again tomorrow. Or, alternatively, subsequent changes can be effected by changing the value of the variable and importing that into the desired target chapter files...
    Cheers & hope this helps,
    Riley

  • Replacing soft returns with hard returns in search and replace PM7

    How do I search and replace soft returns in PM7 with a
    hard return? What do I type in the find box?

    Yes BigJohnD,
    That is the answer! Thanks so much.
    I had hunted for that chart but had not found it yet.
    Thanks again, You have been so helpful.
    MargoHollis

  • Search and Replace String throwing the wrong error message with regexp?

    This came up in a LAVA thread, and I'm not sure if there's a bug here or not. When using Search and Replace string, and using a regular expression of [(G[b|i])], LabVIEW throws error -4622, "There is an unmatched parenthesis in a regular expression."  There are obviously no unmatched parenthesis in that expression, so it seems to me that the wrong error is being thrown. I'm just not sure if that's a syntactically valid regexp. The problem seems to be with nesting [ ]'s inside ( )'s inside [ ]'s. I've tried a couple of regexp resources on the Web, and one suggests it's valid, while the other seems to think it isn't.
    Message Edited by eaolson on 03-13-2007 10:33 AM
    Attachments:
    ATML_StandardUnit2.vi ‏10 KB
    regexp.png ‏5 KB

    adambrewster wrote:
    I think your regexp is invalid.
    In regexps, brackets are not the same as parentheses.  Parens are for grouping, while brackets are for matching one of a class of characters.  Brackets can not be nested.
    If the regexp is replaced with [G[bi]], there is no error, so it's not a matter of nested brackets. I couldn't find anything on the PCRE man page that forbids nested brackets specifically, but it makes sense.
    Your expression "[(G[bi])]", therefore parses as a character class which matches '(', 'G', '[', 'b', or 'i' followed by an unmatched paren, and an unmatched bracket.
    I don't believe that's the case. Replace the regexp with [(Gbi)], and the error goes away. So it's not a matter of the '(' being literal, and then encountering a ')' without a matching '('.
    daveTW wrote:
    what string exactly you want to replace? I think the round braces are not right in this case, since they mark partial matches which are given back by "match regular expression". But you don't want to extract parts of the string, you want to replace them (or delete, with empty <replace string>). So if you leave the outer [( ... )] then your RegEx means all strings with either "Gb" or "Gi".
    It's not my regular expression. A poster at LAVA was having problems with one of his (a truly frightening one), and this seemed to be the element that was causing the problem. I'm pretty sure that the originator of the regexp meant to use G(b|i), which seems like a complicated way of matching "Gb" or "Gi", if you ask me.

  • Search and Replace help. Please

    I have imported some text where in the original there is italic content but when bringing into IDCS4 that italic text shows up as _italic words_. That is as roman with _ characters surrounding it. Is there a way to search and replace. Needless to say the text between the _s varies.

    I would try a GREP find/change searching for (_)([^_]+)(_) and replace with $2 Set the change formatting to italics (preferably as a character style).  This translates to look for a _, then anything that is not a _, followed by another _, and replace with only the stuff in between. You can also use (_)(.+?)(_) which would match the shortest srting in between two _ characters in the same way (except it won't cross a paragraph break), but it will run a bit slower.
    Credit for this should go to Peter Kahrel and his excellent GREP primer....

  • Search and Replace "Column Break" with "Page Break"?

    Hi,
    I have been using the "column break" where I really should have been using the "page break". The page break just makes more sense in my layout.
    Is there anyway to search and replace the column break with a page break?
    Thanks,
    Rhek

  • Search and replace formulas with AppleScript

    Thanks to this forum I've found out that it is possible to search and replace text by other text or formulas with AppleScript in Numbers 3.2
    Does anybody have a script to search and replace a formula or a part of a formula by another formula or a partial formula.
    For example:
    I would like to be able to find:
    = Table1::$b$3
    and replace this by:
    = Table1::$b$4

    De Signature,
    Would this approach work for you...
    This is a very neat way edit a complex formula in a single cell....
    a) Copy and Paste the formula to a new black page in Pages,
    b) Do your Find and Replace, then
    c) Copy and Paste the formulae back into the cell in Numbers.
    It works like a charm.
    Here is an example of how I used this approach...
    Original cell formulae:
    =AVERAGE(
    SMALL(OFFSET(K3,1,0,20,1),1),SMALL(OFFSET(K3,1,0,20,1),2),
    SMALL(OFFSET(K3,1,0,20,1),3),SMALL(OFFSET(K3,1,0,20,1),4),
    SMALL(OFFSET(K3,1,0,20,1),5),SMALL(OFFSET(K3,1,0,20,1),6),
    SMALL(OFFSET(K3,1,0,20,1),7),SMALL(OFFSET(K3,1,0,20,1),8))
    Final version of formulae:
    =AVERAGE(
    SMALL(OFFSET(K3,N1,0,20,1),1),SMALL(OFFSET(K3,N1,0,20,1),2),
    SMALL(OFFSET(K3,N1,0,20,1),3),SMALL(OFFSET(K3,N1,0,20,1),4),
    SMALL(OFFSET(K3,N1,0,20,1),5),SMALL(OFFSET(K3,N1,0,20,1),6),
    SMALL(OFFSET(K3,N1,0,20,1),7),SMALL(OFFSET(K3,N1,0,20,1),8))
    Find Replace: be cautious with the Find, to ensure it is unique, in my this example ",1,", to avoid changing the" ,1)"
    Enjoy...

  • Search and replace with wildcard?

    I always use search and replace with Homesite but I wonder if
    there is a way of using a wildcard? I often want to replace text at
    the beginning and end of variable text. I mean, if I have this:
    <h3>First text</h3>
    <h3>Second text here</h3>
    What I'd like is, using the * as a wildcard, is to use
    something like this:
    Replace <h3>*</h3> with <h2>*</h2>
    Any ideas? Thanks

    Make a backup first, in case this doesn't work (although it should).
    Use this in the Find field:
    countryText = "([^"]*)";
    And this in the Replace field:
    <countryText>$1</countryText>

  • Using a variable in a Powershell search and replace string

    Hi
    a couple of days ago I posted a question about doing a search and replace with wildcards
    Search and repalce with Widcards
    I got a swift and very helpful answer but now I need to build on it.
    In a text file I wanted to replace all the text between two defined words.  the script I got was this
    $text = 'Some Server this bit of text varies Language stuff'
    $text -replace '(.*Server) .+? (Language.*)','$1 it will always say this $2'
    It works great but now I want to replace "it will always say this" with a variable and I can't figure out the correct grammar to make this happen.
    Can anyone help??
    Thanks
    Alex

    Here's one way:
    $replace = 'it will aways say this'if ( $text -match '(.*Server) .+? (Language.*)' )
    { "{0} $Replace {1}" -f $matches[1,2] }
    else { $text }
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

Maybe you are looking for

  • ICal in Leopard has GUI Issues

    Has anyone noticed that the date, in the Dock on iCal and when using command tab to cycle thru apps, is not flushed to the bottom white area of the calendar icon but crosses over to the red top section? There are also 2 "Help"s in iCal's menu bar. Is

  • Facebook will not boot up on my iPad but works on my iPhone ??  Please help

    MY Facebook app has not been able to boot up on my iPad since Thursday. It works fine on my iPhone but I just get a blank white screen with a blue border across the header. After a few seconds it just goes back to iPad menu. I have deleted an re inst

  • How do I convert unreadable dvd files to iMovie?

    I'm sure this question has been asked before, but I cannot find anything relevant in a search.  I burned a DVD from a VHS tape.  Now I'd like to convert it to iMovie so that I can upload a segment onto my iPhone.  QuickTime won't recognize the format

  • Edit will not display content only background picture

    I have five pages linked - three work fine when I go to edit. the other two only display the background picture (two different pictures) but no content. I have tried all I know to fix it. Any ideas out there?  contribute CS4 Ver. 5

  • Capturing hour 1 of a tape

    So I had some film transferred to D5 and DVCam. I tried to capture the DVCam to offline and I had some problems. I had 12 minutes and 30 seconds of footage on the DVCam (no FLEX file). So I set the capture tool to bring in hour 01:00:00:00-01:12:30:0