I want to replace a word with another word in a text file.

file.txt :

alireza fallah

my code :

cat file.txt | tr ali ALI

but I get this :


it replace all 'a's to 'A' , and 'l's to 'L' and 'i's to 'I' .

is there any way to replace just 'ali' to 'ALI' ?

1 Answer 1


This task is easier with GNU sed:

$ sed -i 's/ali/ALI/' file.txt

because tr operates on character sets rather than strings.

To avoid unwanted replacements while echoing, try specifying the exact position of the word to be replaced and or a regular expression that matches only the string you are interested in:

$ printf "cali\nali\nwali\nmali.\n" | grep -E '^ali' | tr ali ALI
  • thanks , cant it be done by tr ? Sep 26, 2013 at 13:28
  • sed -i replaces the word in original file , i just want to echo it Sep 26, 2013 at 13:35
  • Well, you Q says:"I want to replace a word with another word in a text file."
    – dawud
    Sep 26, 2013 at 13:37
  • WELL , excuse me ! Sep 26, 2013 at 13:38
  • 1
    I have added an example using trthat doesn't alter the original file.
    – dawud
    Sep 26, 2013 at 13:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .