Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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

share|improve this question

4 Answers 4

up vote 55 down vote accepted
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

share|improve this answer
1  
Man, you're a legend! Tks heaps! –  medina Mar 13 at 5:40
    
Ahh, I knew "SED" was the right answer. I've found many answers to this question around, many involving sed, but they often were far more complicated calls. This feels RIGHT. +1. –  Doc Aug 5 at 21:31

Through awk's gsub command,

awk '{gsub(/pattern/,"replacement")}' file

Example:

awk '{gsub(/1/,"0");}' file

In the above example, all the 1's are replaced by 0's irrespective of the column where it located.


If you want to done a replacement on a specific column then do like this,

awk '{gsub(/pattern/,"replacement",column_number)}' file

Example:

awk '{gsub(/1/,"0",$1);}' file

It replaces 1 with 0 on the column 1 only.

share|improve this answer

Simple/classic command tr.

From man tr:

tr - translate or delete characters


You can use as following:

tr 'string to be converted' 'string to replace' <file.txt |tee file.txt

where |tee is useful to get out-put on screen as well as to redirect to file.

share|improve this answer
    
The question asks about replacing words; tr converts every individual character from the first string to the corresponding character in the second string. So in your example, every 'b' in the file becomes an 'r'; every space becomes a 'p'; and so forth. –  cscarney Aug 5 at 22:33
    
echo 'hello world' | tr 'hello' 'goodbye' produces goddb wbrdd –  cscarney Aug 5 at 22:40

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
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.