Search and replace using bash script?

kyiosus

Registered
Hello, I'm kind of a bash newbie, so I'm wondering if anyone could help me out on this. Say I have a txt file saved somewhere, and I would like to replace certain words within that file (using the terminal) and then copy the file with the replaced words somewhere else. Is this possible? Thank you for your help!
 
The 'sed' command will do the trick. Say for example you have a text file "input.txt" and you want to replace every occurance of the word "Hello" with "Goodbye". The output will be in "output.txt". In the terminal, you can do:

Code:
sed 's/Hello/Goodbye/g' input.txt > output.txt

In the sed command string "s/Hello/Goodbye/g", 's' means substitute, and the 'g' means substitute every occurance. If you omit the g only the first occurance of "Hello" on any given line will be replaced.

Check out the man page (in the terminal issue the command "man sed' without the quotes), or do a web search for "sed" for more information.
 
Back
Top