Replace a string within text file to another string

hi everybody
i wich to replace some word writed in text file to another word,,,,for example i want to replace all word when the word is "SOLARIS" to "solaris" .
anyone have an idea to resolve this prob via command or script,plz respond me.
thanks

To elaborate on alan.pae's response:
sed 's/SOLARIS/solaris/g' oldfilename > newfilename
-systemstate

Similar Messages

  • Copy one text file to another text file and delete last line

    Hi all wonder if someone can help, i want to be able to copy one text file to another text file and remove the last line of the first text file. So currently i have this method:
    Writer output = null;
             File file = new File("playerData.xml");
             try {
                   output = new BufferedWriter(new FileWriter(file, true));
                   output.write("\t" + "<player>" + "\n");
                   output.write("\t" + "\t" + "<playerName>" + playerName + "</playerName>" + "\n");
                   output.write("\t" + "\t" + "<playerScore>" + pointCount + "</playerScore>" + "\n");
                   output.write("\t" + "\t" + "<playerTime>" + minutes + " minutes " + seconds + " seconds" + "</playerTime>" + "\n");
                   output.write("\t" + "</player>" + "\n");
                   output.write("</indianaTuxPlayer>" + "\n");
                  output.close();
                  System.out.println("Player data saved!");
             catch (IOException e) {
                   e.printStackTrace();
              }However each time the method is run i get the "</indianaTuxPlayer>" line repeated, now when i come to read this in as a java file i get errors becuase its not well formed. So my idea is to copy the original file, remove the last line of that file, so the </indianaTuxPlayer> line and then add this to a new file with the next data saved in it. So i would end up with something like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <indianaTuxPlayers>
         <player>
              <playerName>Default Player</playerName>
              <playerScore>0</playerScore>
              <playerTime>null minutes null seconds</playerTime>
         </player>
         <player>
              <playerName>Default Player</playerName>
              <playerScore>0</playerScore>
              <playerTime>null minutes null seconds</playerTime>
         </player>
         <player>
              <playerName>Default Player</playerName>
              <playerScore>0</playerScore>
              <playerTime>null minutes null seconds</playerTime>
         </player>
    </indianaTuxPlayers>
    However after all day searching the internet and trying ways, i have been unable to get anything working, could anyone give me a hand please?

    I would go the XML route too, but for fun, open a file as a BufferedWriter and do this:
    void copyAllButLastLine(File src, BufferedWriter tgt) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader(src));
        try {
            String previous= in.readLine();
            for (String current = null; (current = in.readLine()) != null; previous=current) {
                tgt.write(previous);
                tgt.newLine();
        } finally {
            in.close();
    }

  • What is the best way of replacing words in a text file ?

    i want to read in a text file and when i come across a certain word, i want to change it to something else. Whats the best way to do this ?
    If i read in a line at a time, how would i only replace one word and not the rest of the line ?
    thanks

    thanks it works !!! But i wrote the contents to a new file.
    How do i overwrite the same file ? I put the the input and output file as the same location but it overwrites the original file with a blank one.
    i guess i have to write into another buffer and read all lines first before overwriting the file right ? how should i do that ?
    also, i only want to overwrite the file ONLY if applies replaceAll method, otherwise if no replacing takes place i dont want to keep updating the file everytime.

  • How to replace a line ina text file using java?

    Hi ALL,
    Does anybody know how to replace a line in a text file uisng java.

    use this thing:
    http://doesthatevencompile.com/current-projects/code-sniplets/ASCIIFile.htm
    open the file,
    read its contents, replace the text you need in the contents, set the contents back into the file.
    it takes care of the IO for you.

  • Email a regular text file from another mac?

    Hi guys,
    I'd like to start working on a small project which will make life a little easier for me.
    I need to send myself a text file once a week from my work computer (iMac 10.6.2) - outside of working hours (around 6pm on a Friday - every Friday).
    I've been looking around for the best way to do this, and have in the past had a small amount of success with AppleScript. Though I understand a better way may be to use a Cron or Launchd for the job.
    I'll need it to be reliable, and "if possible" email me the file even if someone logs me out of the work iMac (???).
    I'd appreciate some input as to where I start with this project!
    Thanks in advance.

    This may work, assuming that the file you want to get is just a plain text file. copy the following into a plain text editor (be careful not to save it in rich text or any styled text format; has to be plain text).
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
    <key>AbandonProcessGroup</key>
    <true/>
    <key>Disabled</key>
    <false/>
    <key>Label</key>
    <string>my.sendMeMail</string>
    <key>ProgramArguments</key>
    <array>
    <string>mail</string>
    <string>-s</string>
    <string>Mail from work</string>
    <string>[email protected]</string>
    <string>&lt;</string>
    <string>/path/to/file</string>
    </array>
    <key>StartCalendarInterval</key>
    <array>
    <dict>
    <key>Weekday</key>
    <integer>5</integer>
    <key>Hour</key>
    <integer>18</integer>
    <key>Minute</key>
    <integer>0</integer>
    </dict>
    </array>
    </dict>
    </plist>
    Edit it to have your email and the path to your file, save it as my.sendMeMail.plist (or something) in /Library/LaunchDaemons, and hen run the following command in terminal: {color:blue}launchctl load /Library/Launchdaemons/my.sendMeMail.plist{color}. (if you want to remove the job, incidentally, take the plist out of the LaunchDaemons folder, and run {color:blue}launchctl remove my.sendMeMail{color} in terminal).
    this should send you an email every friday at 6:00 which has the text of the file as the body of the email. it's not an attachment if you need an attachment (say because your file isn't a text file) then you'll need to do something more complex in terminal, like uuencoding the file or building a mime message. You'll also need to make sure that the file permissions are such that the system can access and read the file.
    If you could be sure your account was active you could script apple mail, but if someone else is logged in, that won't work
    Message was edited by: twtwtw

  • Appending one text file to another

    Hi,
    I have a huge text file which is basically a load of Spam email. I've now got more text files of spam that I want to append onto the old one. I can't for the life of me remember how to do it at the command line. Can anyone help?
    Cheers,
    Stu

    cat file1 file2 > file3
    concatenates file1 and file2 and writes the result to file3.

  • Replacing word in a text  file...in java

    hello;
    could anyone plz help me in writing a program in java that will replace a specific word with a specific word?Though i can read and write to a file. I need it urgently....plz help me...
    regards
    [email protected]

    public class wordReplace {
    public static void main(String [] args)
    String oldStr = "They can do it easily..." ;
    String newStr = oldStr.replaceAll("They", "You");
    System.out.println(newStr);
    }

  • How do I send a text file from one device to another?

    Hi,
    I'm working on an Android Air app made in CS5.5 where user data is saved in the app's applicationStorageDirectory as a text file.
    Is there a way to send this saved text file to another device's applicationStorageDirectory via Bluetooth/email/text e.g?
    The idea is that the app "game" is saved on each person's device. When the game is over, I want the users to be able to compare their results. (I'll write some code to compute who the winner is via comparing the two results)
    Any help is greatly appreciated. Some code sample would be terriffic.
    Thanks,
    J.D.

    You're in native extension territory. Access to things like bluetooth are well beyond the scope of the AIR framework. You'd need to write a native extension, which is code that taps into the native functionality of the device to expand flash's abilities, to use something like bluetooth.
    For you to share locally it most likely may need you to use push notifications, which are perfectly possible, even on wifi.

  • Save tree structure to text file and load textfile to another tree control

    I'm able to save the structure and data to a text file, thanks to the "save tree structure to textfile" info found on this msg board, but can't seem to load the complete tree structure data from the text file into another tree. I've only been able to load parent data but can't get the hierarchy of the tree with the indents and child data to work.
    Thanks

    Thanks Tanya,
    However, I'm still stumped on how to copy (from text file) to other columns in the tree (from one tree to another).  I can only get the first column to load.
    I've attached my working VI and a textfile that I use to load into the "User list" tree.
    Rick
    Attachments:
    Text File to Tree V2.2.vi ‏58 KB
    test file save16.txt ‏1 KB

  • DOWNLOADING A REPORT PROGRAM CODE IN TO TEXT FILE

    I HAVE ONE SIMPLE REPORT PROGRAM SAY,
    *& Report  ZTEST25
    REPORT  ZTEST25.
    DATA : A(8) TYPE C.
    A = 'ANDHRA'.
    WRITE  A.
    THE ABOVE MENTIONED REPORT PROGRAM SHOULD BE DOWNLOADED TO A TEXT FILE USING ANOTHER REPORT PROGRAM BY USING PARAMETER.
    THE OUTPUT IN THE FLAT FILE SHOULD BE:
    REPORT  ZTEST25.
    DATA : A(8) TYPE C.
    A = 'ANDHRA'.
    WRITE  A.

    here is complete code for  that
    report  z11dpk_assign1
            no standard page heading
            message-id z11dpk
            line-size  200                 "page width
            line-count 65(0).              "page length.
    T  A  B  L  E S  D  E  C  L  A  R  A  T  I  O  N                  *
    tables:  trdir,     " System Table TRDIR
             trdirt.    " Title texts for programs in
    D  A  T  A  D  E  C  L  A  R  A  T  I  O  N                       *
    Types
    Structure declaration for system table
    types: begin of struct_sys,
           name(40) type c,       " ABAP program name
           clas(4)  type c,       " Program class
           subc(1)  type c,       " Program type
           cnam(12) type c,       " Author
           cdat     type dats,    " Created on
           rstat(1) type c,       " status
           text     type repti,   " Report title
           c_box(1) type c,       " for check box
           end of struct_sys.
    Structure for internal table for report data
    types: begin of struct_report,
           line(500),
           end of struct_report.
    C  O  N  S  T  A  N  T  S  D  E  C  L  A  R  A  T  I  O  N  S
    data     : c_name(50)        type c,               " Program Name
               c_filename        like ibipparms-path,  " File name
               c_filename1       type string,          " File name
               c_ext(5)          value '.TXT',         " File extension
               c_textline(150)   type c,               " downloading status
               c_count           type c,               " no of pgm downlded
               c_count_text(100) type c.               " Text pgm downlded
    The CONSTANTS statement defines global and local constants.
    By using constants, you can read statically declared data objects,
    constants: c_const(8)        value 'UNTITLED'.
    I  N  T  E  R  N  A  L  T  A  B  L  E  D  E  C  L  A  R  A  T  I  O N
    data: it_sys    type standard table of struct_sys, " Itab for sys data
          it_report type standard table of struct_report with
          non-unique default key initial size 1000.    " Itab for rep data
    W  O  R  K  A  R  E  D  E  C  L  A  R  A  T  I  O  N  S
    data: wa_sys    type struct_sys,          " Work area for sys data
          wa_report type struct_report.       " Work area for report data
    I  N  I  T  I  A  L  I  Z  T  I  O  N
    initialization.
      clear  : wa_sys.
      refresh: it_sys,
               it_report.
      c_count = 0.
    S  E  L  E  C  T  I  O  N  -  S  C  R  E  E  N
      selection-screen  : begin of block blk3 with frame title text-015.
      selection-screen  : begin of block blk1 with frame title text-001.
      select-options    : s_name for trdir-name.              " Program name
      selection-screen  : end of block blk1.
      selection-screen  : begin of block blk2 with frame title text-002.
      parameters        : p_file type rlgrap-filename. " Path for loc folder
      selection-screen  : end of block blk2.
      selection-screen  : end of block blk3.
    A  T  S  E  L  E  C  T  I  O  N  -  S  C  R  E  E  N
    *The possible entries pushbutton for F4 appears beside the appropriate
    *fld (p_file) When the user activates this pushbutton or presses F4 for
    *the fld, the event is executed You can thus implement a self-programmed
    *possible entries routine for the input/output fields of the selection
    *screen
    at selection-screen on value-request for p_file.
    Value of Local file for upload/download is obtained by using this FM
      call function 'F4_FILENAME'
        importing
          file_name = p_file.
    S  T  A  R  T  -  O  F  -  S  E  L  E  C  T  I  O  N
    start-of-selection.
    CONCATENATE p_name '%' INTO z_name.
      select name
             clas
             subc
             cnam
             cdat
             rstat into table it_sys
                   from trdir
    *Sorts the selected records in ascending order by the specified column
    *references f1 ... fn (name)
                  where name in s_name order by name.
                  WHERE name LIKE 'Z11%'.
      if sy-subrc = 0.
        sort it_sys by name.
        clear wa_sys.
        loop at it_sys into wa_sys.
          select single text
                 into wa_sys-text
                 from trdirt
                 where name  = wa_sys-name and
                       sprsl = sy-langu.
          modify it_sys from wa_sys index sy-tabix.
          clear wa_sys.
        endloop.
      endif.
      set pf-status 'MENU_ASSIGN1'.
      uline.
      write:/    sy-vline ,
             8   sy-vline,  text-009 color 4,         " Name of the Program
             55  sy-vline,  text-003 color 4,         " Class
             62  sy-vline,  text-004 color 4,         " Type
             68  sy-vline,  text-005 color 4,         " Created By
             80  sy-vline,  text-006 color 4,         " Created On
             92  sy-vline,  text-007 color 4,         " Status
             100 sy-vline,  text-008 color 4,         " Program text
             180 sy-vline.
      clear wa_sys.
      loop at it_sys into wa_sys.
        uline.
        write:/ sy-vline,
               5   wa_sys-c_box as checkbox,
               8   sy-vline,  wa_sys-name,
               55  sy-vline,  wa_sys-clas,
               62  sy-vline,  wa_sys-subc,
               68  sy-vline,  wa_sys-cnam,
               80  sy-vline,  wa_sys-cdat,
               92  sy-vline,  wa_sys-rstat,
               100 sy-vline,  wa_sys-text,
               180 sy-vline.
      endloop.
    at user-command.
      case sy-ucomm.
        when 'BACK'.
          leave screen.
        when 'EXIT'.
          leave program.
        when 'DOWN'.
          clear wa_sys.
          do.
            clear wa_sys.
            read line sy-index field value wa_sys-c_box wa_sys-name.
            if sy-subrc <> 0.
              exit.
            endif.
    *if check box is selected.....
            if wa_sys-c_box = 'X'.
              clear c_textline.
    *Assigns the contents of the source field to the target field as a new
    *value
              write text-010    to c_textline.         " Downloading
              write wa_sys-name to c_textline+12.
              write text-011    to c_textline+53.      "to
              write c_filename1 to c_textline+56.      " file name
    FM returns the Text to be displayed on screen
              call function 'SAPGUI_PROGRESS_INDICATOR'
                exporting
                  text = c_textline.
              c_count = c_count + 1.
    Reads the program prog from the database into the internal table itab.
    The line length of table itab should be at least 72 characters
              read report wa_sys-name into it_report.
              if sy-subrc <> 0.
                exit.
              endif.
    *p_file contains the character string untitiled
    This comparison is not case sensitive
              if p_file cs c_const.        " Untitled
    the string ''(space) replaces the untitled occurrence of the search
    ignore case is used as this search is case sensitive
                replace c_const in p_file with '' ignoring case.
              endif.
    Places the fields f1 to fn (n >= 2) after g (target field).
              concatenate p_file wa_sys-name  c_ext into c_filename1.
    *Data transmission of an internal table from the server to a file on the
    PC is done by this FM.
              call function 'GUI_DOWNLOAD'
                exporting
                  filename = c_filename1
                  filetype = 'ASC'
                tables
                  data_tab = it_report.
              if sy-subrc <> 0.
                message id sy-msgid type sy-msgty number sy-msgno
                        with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
              endif.
            endif.
          enddo.
          clear c_count_text.
          write c_count  to c_count_text+1.
          write text-030 to c_count_text+4.
    Nos Of Pgms downlded successfully
          message i205 with c_count_text.
      endcase.
    T  O  P -  O  F  -  P  A  G  E
    top-of-page.
      uline.
      write:/   sy-vline,
             10 text-020 color 2,  " Fujitsu India Limited
             70 text-021 color 2.  " List of ABAP Programs
      write:/   sy-vline,
             10 text-022 color 3, sy-datum color 3,    " Date
             70 text-023 color 3, sy-pagno color 3.    " Page No
    plz reward if helpful
    vivek

  • Setup JFileChooser to accept text files only.

    Hello all, I was trying to setup a JFileChooser to accept only text files, so here's the code:
    JFileChooser my_filec = new JFileChooser();
            my_filec.addChoosableFileFilter(new FileFilter()
                public boolean accept(File f)
                    return (f.getName().endsWith(".txt")|| !f.getName().contains("."));
                public String getDescription()
                    return "Text File (*.txt)";
            });and the problem is if I write <return f.getName().endsWith(".txt")> only it can't open foders and when I write <return (f.getName().endsWith(".txt")|| !f.getName().contains("."));>
    it can choose files that doesn't have an extension, is there a way to make it choose ONLY folders and text files?
    Another question, can I setup JFileChooser to check the file itself if it was a text file written in ANSI for example REGARDLESS of its extension?

    return (f.getName().toLowerCase().endsWith(".txt") || f.isDirectory());You can open the file and check whatever you wish.
    The question is how are you going to decide if the file is a text file or not?
    You should also try to keep accept function as short as possible or your file chooser will work very slowly.

  • Accesing file in another package

    I am using Netbeans 6.0 and I am currently accessing another text file in another package called "files" like so:
    br = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("\\files\\"+filename)));This works fine and finds the files when I run the code but it doesn't find the files when I build the jar file and run it separately.
    Any idea what could be happening?

    In a JAR, paths that start with a slash like:
    getResourceAsStream("/a/b/c/d.txt")Start at the "root" of the jar. For this to find the resource, verify that /a/b/c/d.txt is in the JAR.

  • Reading text file, Replace string, Write to new file....

    I'm kind a lost of on this problem. Using the BufferedReader class and BufferedWriter class, develop an application that reads lines of text from a file. Replace any occurrence of the word *?the?* with *?JAVAJAVA?* and change all characters to upper case before writing each line to a different text file named outfile.txt. Finally, have your application use the appropriate method on the File class to return the absolute path of the outfile.txt file and output the path to the screen.
    * Created December 10, 2008
    * @author Fausto Rivera
    * Colorado Technical University - Online Campus
    * IT271-0804B-02 Intermediate Object Oriented Programming II
    * Phase 2 IP
    * Instructor: Cheryl B Frederick
    import java.io.File;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    public class FRiveraReader {
          public static void main(String[] args) {
          // instantiated a new application object to initialize the application
          FRiveraReader application = new FRiveraReader();}
    //      application.getReadfr();  // call to openFile method
    //      application.doWritefr(); // call to readRecords method
    //      application.closeFile();  // call to closeFile method
    public FRiveraReader(){}
      public void getReadfr (String friveraInfile, String fr []){
       int i;
       File fileName = makeAbsoluteFilename(friveraInfile);
       try{
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        String line = reader.readLine();
         i=0;
          while (line != null) {
           fr[i] =line;
           line = reader.readLine();
        i++;
      reader.close();
    catch(IOException e) {
    System.out.println("Error with reading file:" + friveraInfile);
    }//end of getOrder method
    public void doWritefr(String friveraOutfile, String fw[]){//String name of file, String array to be written
    int i;
    File fileNameout = makeAbsoluteFilename(friveraOutfile);
    try {
    BufferedWriter writer = new BufferedWriter(new FileWriter (fileNameout));
      i=0;
      while (fw[i] != null) {
       writer.write(fw[i] + "%n"); //need delimiters between data in file;also, reader reads a line
       i++;
      writer.close();
    catch(FileNotFoundException e) {
    System.out.println("File not found");
    catch(IOException e) {
    System.out.println("Error with reading file:" + friveraOutfile);
    }//end of getOrder method
    private File makeAbsoluteFilename(String friveraOutfile)//these 2 classes used to resolve file name
            File file = new File(friveraOutfile);
            if(!file.isAbsolute()) {
                file = new File(friveraOutfile);
            return file;

    I have modified my code as far as being able to create a text file, write to string, and change to upper case. Now, how can I connected input to the output stream and then replace all the instances of the string "the" for the string "JAVAJAVA"? When the file is created, it goes into a loop writing the following:
    nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%nJAVA.IO.BUFFEREDWRITER@19821F%
    Here is my modified code
    import java.io.File;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    public class FRiveraReader {
    public FRiveraReader() {}
    private static final String inFile = "C:\\Documents and Settings\\Fausto Rivera\\My Documents\\NetBeansProjects\\Rivera_F_IT271_0804B_02_PH2_IP\\friverainfile.txt";//the path name of your file
      public void myReadfr (){
       try {
        BufferedReader reader = new BufferedReader(new FileReader(inFile));
        //String "JAVAJAVA" = String "the";
        System.out.println(inFile);
        String line = reader.readLine();
          while (reader != null) {
           line = reader.readLine();
      reader.close();
    catch(IOException e) {
    System.out.println("Error with reading file:" + inFile);
    }//end of myReadfr method
    public void myWritefr(){//String name of file, String array to be written
    File outFile = new File ("C:\\Documents and Settings\\Fausto Rivera\\My Documents\\NetBeansProjects\\Rivera_F_IT271_0804B_02_PH2_IP\\myoutFile.txt");
    try {
    BufferedWriter writer = new BufferedWriter(new FileWriter (outFile));
    String newline = writer.toString() .toUpperCase();
      while (writer != null) {
       writer.write(newline + "%n"); //need delimiters between data in file;also, reader reads a line
      writer.close();
    catch(FileNotFoundException e) {
    System.out.println("File not found");
    catch(IOException e) {
    System.out.println("Error writing file:" + outFile);
    }//end of getOrder method
    private File makeAbsoluteFilename(String myoutFile)//these 2 classes used to resolve file name
            File file = new File(myoutFile);
            if(!file.isAbsolute()) {
                file = new File(myoutFile);
            return file;
      }Edited by: FRiveraJr on Dec 17, 2008 12:10 PM

  • Replace String within a file

    i want to replace a string within a file
    there is NO GUI ..
    i take in mind two approaches
    1) hold the file content in memory
    and rewrite the file
    2) write the new data to a new file.
    and then rewrite the original file
    any better ideas

    sorry, no..
    Your idea is kinda right if small file is within existance..
    Small file.
    Why not just use the filereader and filewriter? read the docs upon that
    Large file
    Why wont you create a string buffer, and parse the file chunk by chunk into that buffer one at a time. Then of course you saved the position of the character or word you wanted to apend or write, and you just write it back to that area.

  • How to replace a string in a text file?

    Hi All,
    i read one text file and based on that i replaced the old character with the new string but it doesnt works.do any one of you have idea on this?
    My Code:
    String newPassword=(String) getInputText1().getValue();
    String password=(String)getSimNo().getValue();
    String sampleText = (String) getMobileNo().getValue();
    FileReader fr =new FileReader("c:/newLogin.txt");
    BufferedReader br =new BufferedReader(fr);
    String record=br.readLine();
    while (record !=null)
    String[] afterSplit=record.split(":");
    for (int p = 0; p < 1; p++) {
    String userName=afterSplit[1];
    String passWord=afterSplit[3];
    if(userText.equals(userName) && password.equals(passWord)) {
    passWord.replaceAll(passWord,newPassword);
    System.out.println("password: " + password +" changed to : "+ newPassword +" successfully");
    record =br.readLine();
    sample fiile in the text:
    userName:sebas:password:navin
    userName:sebas1:password:navin1

    All readLine does is copy a line of the file into a local variable. Change the copy as you will, the file won't change.
    You need to write a new version of the file, with the altered lines. Then, if required, you can delete the original file and rename the new file to the old file name.

Maybe you are looking for