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
add comment

2 Answers

up vote 37 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
    
Man, you're a legend! Tks heaps! –  medina Mar 13 at 5:40
add comment

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
add comment

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.