Replace token in an File

Hi,
I'm searching for an easy way to change specific tokens in a file. For instance an HTML file specify <img src="http://www.site1.com/images/img.gif"> I would like to replace all occurences by
<img src="http://www.site2.com/imgs/old/img.gif"> for instance.
Is there an easy way to do this ? (streamtokenizer or something)
Examples are welcome,
Stephane

Hi Steve! One quick observation, if I may. Consider the following lines of code.
pos += o.length();
oldpos = pos;
pos does not need to be updated as above. Rather, you just need
oldpos = pos + o.length();That's because pos is being updated at the top of the loop. Also, you can move the declaration of pos out of the loop. The same applies for the creation of the StringBuffer object.
Here's a slightly different version of the code. If you can optimize it further, please let me know.
   public static String replace( String s, String oldToken, String newToken, boolean fAll )
      if ( ( s == null ) || ( oldToken == null ) || ( newToken == null ) )
         throw new IllegalArgumentException( "Null argument(s) seen" );
      int oldTokenLen = oldToken.length();
      StringBuffer sb = null;
      int oldPos = 0;
      int pos = s.indexOf( oldToken, oldPos );
      if ( oldPos > -1 )
         sb = new StringBuffer( s.length() );
      for(
          ; pos > -1
          ; pos = s.indexOf( oldToken, oldPos )
         sb.append( s.substring( oldPos, pos ) );
         sb.append( newToken );
         oldPos = pos + oldTokenLen;
         if ( !fAll )
            break;
      return ( ( oldPos > 0 ) ? sb.append( s.substring( oldPos ) ).toString() : s );
   }  // replaceCheers!

Similar Messages

  • Find & Replace text in html files

    This is my first real attempt at using Automator, and it has become increasingly frustrating for me. I love the idea of Automator, nice interface, and it appears to be so easy to use. But, I can't get it to actually DO anything and I don't understand why.
    Here is my goal:
    to batch process multiple html files to remove certain characters and words (or replace them with empty space).
    I currently open these files in Pages and do 6 separate Find & Replace commands for each file before I continue with my other processing tasks. This is very tedious and I believe the computer should be able to find & replace multiple items at one time. (I have used other utilities to do batch renaming and trimming file names before.)
    All I want to do is select a group of files (usually 25 at a time) and have Automator get rid of all the unwanted words and characters before I open each file for final processing in Pages. I found a set of Automator actions for TextEdit which includes a Find & Replace action, but I've wasted over an hour so far trying to get it to work.
    When I run the workflow, it acts like it's doing something, but the files remain unchanged. I have tried using actions such as Read Text File, Get Contents of TextEdit Document, Set Contents of TextEdit Document, along with 6 instances of Find & Replace, but I cannot get it to work.
    I'm at a point today where I cannot afford to mess around with this anymore. I have to do it the long way in Pages or else I'll never get it done, but I want to get these Automator workflows to work before I have to repeat this task. (I do this at least once a week right now.)
    Any ideas or suggestions? I've tried reading in the help menus and support pages, but perhaps I'm just not understanding something here.

    Any ideas or suggestions?
    You might be interested in using TextWrangler. It can perform batch find-and-replace changes across multiple selected files.
    Good luck!
    Andrew99

  • Search and replace strings in a file while ignoring substrings

    Hi:
    I have a java program that searches and replaces strings in a file. It makes a new copy of the file, searches for a string in the copy, replaces the string and renames the new copy to the original file, thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but searching for "Topabcd" and replacing it doesnot work because there is a match for "abcd" in a different search scenario. How can I modify the code such that if "abcd" is already searched and replaced then it should not be searched for again or rather search for "abcd" as entire string and not if its a substring of another string.
    In the below code output, all instances of "abcd" and the ones of "Topabcd" are replaced by ABCDEFG and TopABCDEF respectively, whereas according to the desired output, "abcd" should be replaced by ABCDEFG and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
              String find_productstring = "abcd";
              String replacement_productstring = "ABCDEFG";
              compsXml = new FileReader(compsLoc);
              compsConfigFile = new BufferedReader(compsXml);
              File compsFile =new File("file.xml");
              File compsNewFile =new File("file1.xml");
              BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
              while ((compsLine = compsConfigFile.readLine()) != null)
                    new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
                    out.write(new_compsLine);
                    out.write("\n");
                out.close();
                compsConfigFile.close();
                compsFile.delete();
                compsNewFile.renameTo(compsFile);
            catch (IOException e)
            //since "Topabcd" contains "abcd", which is the search above and hence the string "Topabcd" is not replaced correctly
             try
                   String find_producttopstring = "Topabcd";
                   String replacement_producttopstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
                   compsConfigFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
                   BufferedWriter out =new BufferedWriter(new FileWriter("file1.xml"));
                   while ((compsLine = compsConfigFile.readLine()) != null)
                         new_compsLine =compsLine.replaceFirst(find_producttopstring, replacement_producttopstring);
                         out.write(new_compsLine);
                         out.write("\n");
                     out.close();
                     compsConfigFile.close();
                     compsFile.delete();
                     compsNewFile.renameTo(compsFile);
                 catch (IOException e)
            }Thanks a lot!

    Hi:
    I have a java program that searches and replaces
    strings in a file. It makes a new copy of the file,
    searches for a string in the copy, replaces the
    string and renames the new copy to the original file,
    thereafter deleting the copy.
    Now searching for "abcd", for eg works fine, but
    searching for "Topabcd" and replacing it doesnot work
    because there is a match for "abcd" in a different
    search scenario. How can I modify the code such that
    if "abcd" is already searched and replaced then it
    should not be searched for again or rather search for
    "abcd" as entire string and not if its a substring of
    another string.
    In the below code output, all instances of "abcd" and
    the ones of "Topabcd" are replaced by ABCDEFG and
    TopABCDEF respectively, whereas according to the
    desired output, "abcd" should be replaced by ABCDEFG
    and "Topabcd" should be replaced by REPLACEMEFIRST.
    try
    String find_productstring = "abcd";
    String replacement_productstring = "ABCDEFG";
    compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    BufferedReader(compsXml);
    File compsFile =new File("file.xml");
    File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    FileWriter("file1.xml"));
    while ((compsLine =
    compsConfigFile.readLine()) != null)
    new_compsLine
    =compsLine.replaceFirst(find_productstring,
    replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
    catch (IOException e)
    //since "Topabcd" contains "abcd", which is
    the search above and hence the string "Topabcd" is
    not replaced correctly
    try
                   String find_producttopstring = "Topabcd";
    String replacement_producttopstring =
    topstring = "REPLACEMEFIRST";
                   compsXml = new FileReader(compsLoc);
    compsConfigFile = new
    gFile = new BufferedReader(compsXml);
                   File compsFile =new File("file.xml");
                   File compsNewFile =new File("file1.xml");
    BufferedWriter out =new BufferedWriter(new
    dWriter(new FileWriter("file1.xml"));
    while ((compsLine =
    compsLine = compsConfigFile.readLine()) != null)
    new_compsLine
    new_compsLine
    =compsLine.replaceFirst(find_producttopstring,
    replacement_producttopstring);
    out.write(new_compsLine);
    out.write("\n");
    out.close();
    compsConfigFile.close();
    compsFile.delete();
    compsNewFile.renameTo(compsFile);
                 catch (IOException e)
    Thanks a lot!I tried the matches(...) method but it doesnt seem to work.
    while ((compsLine = compsConfigFile.readLine()) != null)
    if(compsLine.matches(find_productstring))
         System.out.println("Exact match is found for abcd");
         new_compsLine =compsLine.replaceFirst(find_productstring, replacement_productstring);
    out.write(new_compsLine);
    out.write("\n");
         else
         System.out.println("Exact match is not found for abcd");
         out.write(compsLine);
         out.write("\n");

  • How to replace a line in file Java

    Hi,
    I want to replace a line in file sequencial.
    I read file, but i don't know how to replace one line..
    Thanks...

    I supose this..
    I usea a FileReader and BufferedReader to read a file.
    I read a line, I know the number of the line, but how to say to method println o write what it's the line to replace?

  • Acrobat Pro X Replaces Document Title with File Name

    We process many Microsoft Word Documents into PDF. Whether or not this is the correct way to process them we use the new "Action" previously a Batch Process.
    We require our documents to open "Full Width" so we run the created Action which converts the Word files to PDF and sets them to open width.
    In the previous version of Acrobat (9) this worked fine. But the current version strips the document title out of the Word document and replaces it with the file name in the PDF. eg. If the title of the document set in the properties of world.doc is "Changing the world", when the action created the PDF its stripped and replaced with "world.doc"
    This of course means that we must now take the time to change the title of each document so that the search engine on our intranet can correctly list it. As you can imagine a time consuming process, which until this update never had to be done.
    Alternatively is there a better way to convert large numbers of Word documents to PDF that will keep all of this information intact?
    Many thanks
    Murray

    Actions are not really intended for that type of work:
    Actions allow a complex, guided series of events to be applied to a single file, usually with some user interactivity. They can be run over and over but usually only process one file at a time. In the example we show based on redaction, this guided interactivity is essential as only a human can decide what to redact in each document.
    Batch processing applies a standard set of events to a series of files, usually without any user interactivity beyond selection and filename choices.
    What happens when you try and run your Acrobat 9 batch sequence in Acrobat X?

  • Globally Replacing a Noisy Media File with a Cleaned Up File in FCE

    I'm working on a project where I have found that one of my master clips has an audio issue. I've used subclips from this master clip in many places in my video. I'd like to know if thee is a way to process the audio of this master clip and have FCE pickup the cleaned up version of the media automatically for all the subclips used in my sequence. I've found a noise removal effect in a program called Audacity that works quite well to get rid of the noise in my master clip. I'm just not sure about the workflow to get the cleaned up file back into my FCE timeline. Audacity is supposed to work as an external editor in FCE, but haven't been able to get this to work correctly. Here's my proposal:
    1. Place my master clip on new sequence and export the audo tracks to an AIFF file.
    2. Process this file in Audacity using the Audacity Noise Removal effect and save to a .AIFF file.
    3. Import this clean .AIFF file back into FCE.
    4. Repace the audio on the timeline with the cleaned up audio file.
    5. Export this sequence to QTMovie.
    6. Exit FCE and using Finder, replce the original master clip media file in the Capture Scratch directory with the new file with the identical name as the original file
    7. Re launch FCE and hope the program picks up the new file like nothing had changed.
    Does anyone know if this can work as a way to do a global replace on a mdeia file tht needed cleaning up.
    Doug

    Should work as long as both files are the exact same length - the alternative is moving your original file to a new location then using the reconnect menu to navigate to the edited clip.

  • Replace string in a file

    I want a java program can replace string in a file with given string.
    for example,
    my file is
    abc 100
    aaa 110
    ded 123
    replace aaa with mmm.
    my codes is reading line by line and looking for aaa ,if read_line.index("aaa")> -1,then write mmm and aaa.substring
    Do you have ant other solutions?is there any file class method I can use?
    cheers.

    String content = <get file content>;
    String newContent = content.replaceAll( "aaa", "I get my homework on java.sun.com" );
    if( !newContent.equals(content) )
       <rewrite file contents>

  • I wrote an 2500 words assignment and saved in Microsoft word 97-2003 and by mistake replaced with another word file.How can i retain my original work?

    I wrote an 2500 words assignment and saved in Microsoft word 97-2003 and by mistake replaced with another word file.How can i retain my original work? 

    Hi,
    Does this happen to all 97-2003 Word files?
    Word 2013 now has lots of updates compared with earlier version of Word, lots of features have been updated. Use Word 2013 to open documents created in earlier versions of Word (Word 97-2003 format), you will probably encounter unexpected problems,
    expecially for those heavily formatted files.
    We would suggest you to convert your document to the Word 2013 file format, then you will be able to access the new and enhanced features in Word 2013.
    Regards,
    Ethan Hua
    TechNet Community Support
    It's recommended to download and install
    Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
    programs.

  • After an import, replace the init.ora file?

    I have just successfully imported a database from Oracle8i to Oracle10g. Now, is it safe to replace the init.ora file?

    Replace the 10g init file with the 8i? Nope. You should be reading the release notes and upgrade guide, and taking into account the obsolecense of some parameters, the introduction of new ones, etc.
    Also, your control files are probably in a different location, you have different RBS's etc..

  • How can I delete ALL contacts on my iphone and replace with an updated file from my Outlook on PC

    how can I delete ALL contacts on my iphone and replace with an updated file from my Outlook on my PC

    iTunes running, your phone connected, on the Info Pane, scroll down to "Advanced". Put a check in the box labeled "Replace Info on this Phone for Contacts" on next sync. Hit the apply/sync button.

  • I formatted by PC which erased the iTunes software as well. Now when i try to backup my iPad the new iTunes doesn't have access to my existing files. The option is to erase the current content of my iPad and replace it with existing files on my PC.

    I formatted by PC which erased the iTunes software as well. Now when i try to backup my iPad the new iTunes doesn't have access to my existing files. The option is to erase the current content of my iPad and replace it with existing files on my PC. How do i get access to the preivous library?

    Drrhythm2 wrote:
    What's the best solution for this? I
    Copy the entire /Music/iTunes/ folder from her old compouter to /Music/ in her account on this new computer.

  • Multiple replacements from an input file with 1.4 Regex

    hi,
    i'm trying to make multiple replacments to a source file <source> using a second input file <patterns> to hold the regex's. the problem i'm having is that the output file only makes the last replacement listed in the input file. Example if the input file is
    a#123
    b#456
    only b is changed to 456 and a remains.
    the second debug i've got shows that all the replacements are in memory, but i'm not sure how to write them all to the file.
    the syntax is Java MyPatternMatcher <source> <patterns>
    import java.util.regex.*;
    import java.io.*;
    import java.util.*;
    public class MyPatternResolver {
         private File patternFile;
         private File sourceFile;
         private Vector patterns = new Vector();
         public MyPatternResolver(String sourceFile, String patternFile) {
              this.sourceFile = new File(sourceFile);
              this.patternFile = new File(patternFile);
              loadPatterns();
              resolve();
         private void loadPatterns() {
              // read in each line if File
              FileReader fileReader = null;
              try {
                   fileReader = new FileReader(patternFile);
              } catch(FileNotFoundException fnfe) {
                   fnfe.printStackTrace();
              BufferedReader reader = new BufferedReader(fileReader);
              String s = null;
              String[] strArr = new String[2];
              try {
                   while((s = reader.readLine()) != null) {
                        StringTokenizer tokenizer = new StringTokenizer(s, "#");
                        for (int i =0; i < 2; i++) {
                             strArr[i] = tokenizer.nextToken();
                             //Debugging Info
                             System.out.println("Token Value " + i + " = " + strArr);
                             //End Debugging Info
                        patterns.add(new PatternResolver(strArr[0], strArr[1], sourceFile));
              } catch(IOException ioe) {
                        ioe.printStackTrace();
         private void resolve() {
              Iterator iterator = patterns.iterator();
              while(iterator.hasNext()) {
                   PatternResolver pr = (PatternResolver) iterator.next();
                   pr.resolve();
         public static void main(String[] args) {
              MyPatternResolver mpr = new MyPatternResolver(args[0], args[1]);
         public class PatternResolver {
              private String match, replace;
              private File source;
         public PatternResolver(String s1, String s2, File f) {
              this.match = s1;
              this.replace = s2;
              this.source = f;
         public File resolve() {
              File fout = null;
              try {
         //Create a file object with the file name in the argument:
         fout = new File(sourceFile.getName() + "_");
         //Open and input and output stream
         FileInputStream fis = new FileInputStream(sourceFile);
         FileOutputStream fos = new FileOutputStream(fout);
         BufferedReader in = new BufferedReader(new InputStreamReader(fis));
         BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
         // The find and replace statements
         Pattern p = Pattern.compile(match);
                   Matcher m = p.matcher(replace);
                   //Debugging Info
                   System.out.println("Match value = " + match + " Replace value = " + replace);
                   //Debugging Complete
                   String aLine = null;
                   while((aLine = in.readLine()) != null) {
                   m.reset(aLine);
                   //Make replacements
                   String result = m.replaceAll(replace);
                   out.write(result);
              out.newLine();
                   in.close();
                   out.close();
              } catch (Exception e) {
                   e.printStackTrace();
    return fout;

    If your aim is to learn about regex, then its okay.
    Otherwise you might want to check the utility "sed" (stream editor) which does something similar what you are up to. It is a POSIX (.i.e. UNIX) utility, but it is available (in several versions) for other platforms (including Windows) too. (Cf. Cygnus or Mingw).

  • How can I replace an older save file with a new one on game center?

    Greetings,
    I have been trying to change an older game saved file that I have created with my old Ipad with the new one that I have created on my new Ipad, both game files are played under my apple ID but I have no idea how to replace my older one with the new one.
    The new file is superior to the old one so I wish to add the new saved file to my game center.
    The game I am playing is Clash of Clans both file are created on apple products.
    Let me know if there is a sulotion for that case.
    Regards

    Make sure the site folder created by iWeb is named exactly the same as the site folder currently on the server.
    OT

  • Batch code for running a find/replace all on multiple files within a source floder/directory

    What I need is a Batch source code that will open all files in a folder/directory and run a find and replace_all query within them and then save all the files.  The files were created in Illustrator and saved using the Scene7 FXG format extension.    These files will be uploaded into Scene7 as a group after the find and replace macro/query is run on the code.  The same find and replace query will be the same for all the files.  Basically this function or batch process  will save time in setting the same parameters all at one time instead of having to set the parameters individually in scene7.
    a source code sample of the find/replace module macro might be              searchString:  s7:colorvalue="#FFFFFFFF" 
                                                                                                                          replaceString: s7:colorValue="#&txtclr;"
                                                                                                                          searchWhat   "FXG document"    
                                                                                                                             searchSource:  true,
                                                                                                                        useRegularExpressions:   true
    I have no problems creating batch files within Ai and PhotoShop but I have limited programming skills in how to create source code for manuipulating documents outside of those apps or in a OS invironment.
    I could probably come up witha simple program to do what i want for one document but i get lost when dealing with multiple documents in a source folder (prolbem is,  I will be dealing with thousands of documents not 100 or less)
    If anything which Adope cloud app would work best:  Dreamweaver or Edge code   (or just use my notepad)

    What I need is a Batch source code that will open all files in a folder/directory and run a find and replace_all query within them and then save all the files.  The files were created in Illustrator and saved using the Scene7 FXG format extension.    These files will be uploaded into Scene7 as a group after the find and replace macro/query is run on the code.  The same find and replace query will be the same for all the files.  Basically this function or batch process  will save time in setting the same parameters all at one time instead of having to set the parameters individually in scene7.
    a source code sample of the find/replace module macro might be              searchString:  s7:colorvalue="#FFFFFFFF" 
                                                                                                                          replaceString: s7:colorValue="#&txtclr;"
                                                                                                                          searchWhat   "FXG document"    
                                                                                                                             searchSource:  true,
                                                                                                                        useRegularExpressions:   true
    I have no problems creating batch files within Ai and PhotoShop but I have limited programming skills in how to create source code for manuipulating documents outside of those apps or in a OS invironment.
    I could probably come up witha simple program to do what i want for one document but i get lost when dealing with multiple documents in a source folder (prolbem is,  I will be dealing with thousands of documents not 100 or less)
    If anything which Adope cloud app would work best:  Dreamweaver or Edge code   (or just use my notepad)

  • After having my hard drive replaced, I tried restoring files from time machine. The restore completed but I don't know where the files were restored to. I can see they are taking up space on my hard drive but I can't get at them.

    My hard drive failed and so was replaced, luckily everything was backed up on time machine.
    I tried to do a full restore, and it went through the process but I couldn't see my files anywhere on the HD. I tried again and same thing. Eventually I used Migration Assistant and this worked fine.
    However my hard drive is now full - all my previous restores went somewhere but I can't get at them.
    Can anyone please help, I need to delete them from my system.
    Thanks

    Is the HDD in the 2009 15" MBP dead?  (The original source of your data)  If not, you might want ot take it out and put it in an enclosure.
    You might try spotlight on know files to see if that gives you any clues where your data is located.
    You might down load from the Internet OmniDiskSweeper (free) and open it.  It should show you all of the files you have on your MBP and enable to locate them.
    Ciao.

Maybe you are looking for

  • Surface Pro Installation

    Hello all and it's good to be back. I haven't used Arch in a few years or linux for that fact as everything at work required OSX or Windows. Things have changed and I've been able to switch back to Linux. I've been running Ubuntu on my Surface Pro (k

  • Not updating PLA Balance for a month

    We are Extracting PLA Register from  J2I6 for Excise Group XX  , It showed  negative  value in August 2011 , so we went thorough table where PLA balances get updated & can be seen on transaction basis. In Table J_2IACCBAL  , we have found some regist

  • How can I get stored photos off of iphone 5c without backing them up to a computer?

    My son has a 16g 5c and his photos use almost 12g of storage. Can these photos be backed up in iCloud? Do they still count towards storage on the phone if they can be backed up to iCloud? He doesn't want to back them up to our home pc.

  • Compatibility - MSSQL 2005, 64 bit

    We will be performing an upgrade to MSSQL 2005. Has anyone had any problems using 64-bit SQL Server? Does JDBC make this invisible to the ColdFusion client?

  • Do I still need Qmaster?

    I have made the switch to FCP X, Motion 5 and Compressor 4 but still need DVD Studio. I am using a SSD as my boot drive and want to delete any unneccessary files. Do I need to keep Qmaster  on my HD? Thanks.