Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Find and replace text within a file using commands

How can I find and replace specific words in a text file using command line?
by

3 Answers

akshay1995

sed -i 's/original/new/g' file.txt

Explanation:

sed = Stream EDitor
-i = in-place (i.e. save back to the original file)
The command string:

s = the substitute command
original = a regular expression describing the word to replace (or just the word itself)
new = the text to replace it with
g = global (i.e. replace all and not just the first occurrence)
file.txt = the file name
RoliMishra
There are a number of different ways to do this. One is using sed and Regex. SED is a Stream Editor for filtering and transforming text. One example is as follows:

marco@imacs-suck: ~$ echo "The slow brown unicorn jumped over the hyper sleeping dog" > orly
marco@imacs-suck: ~$ sed s/slow/quick/ < orly > yarly
marco@imacs-suck: ~$ cat yarly
The quick brown unicorn jumped over the hyper sleeping dog

Another way which may make more sense than < strin and > strout is with pipes!

marco@imacs-suck: ~$ cat yarly | sed s/unicorn/fox/ | sed s/hyper/lazy/ > nowai
marco@imacs-suck: ~$ cat nowai
The quick brown fox jumped over the lazy sleeping dog
pankajshivnani123
You can use Vim in Ex mode:

ex -s -c '%s/OLD/NEW/g|x' file


% select all lines
s substitute
g replace all instances in each line
x write if changes have been made (they have) and exit

Login / Signup to Answer the Question.