Find the answer to your Linux question:
Results 1 to 3 of 3
I want to replace a word in a text file (file.txt) using shell script. The contents of the file are: file.txt -------------- line one goes here line two is here ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Oct 2010
    Posts
    5

    Edit a file using shell script


    I want to replace a word in a text file (file.txt) using shell script. The contents of the file are:

    file.txt
    --------------
    line one goes here
    line two is here
    and so on........


    I tried following command for replacing a text:
    Code:
    sed -e 's/here/dear/g' file.txt
    It did replace the text but not in the file. I got the replaced text as an output on the console as following.
    Code:
    line one goes dear
    line two is dear
    and so on........
    I want to replace the text in the file. How do I do that?

  2. #2
    Linux Newbie
    Join Date
    Apr 2007
    Posts
    119
    You have to redirect the output to a file and then save that file as the old one.
    Code:
    sed -e 's\here\dear\g' file.txt > filenew.txt
    mv filenew.txt file.txt

  3. #3
    Trusted Penguin Irithori's Avatar
    Join Date
    May 2009
    Location
    Munich
    Posts
    3,440
    sed -i also works, but keep in mind, that this is not portable between different unixes
    You must always face the curtain with a bow.

  4. $spacer_open
    $spacer_close

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •