A message for Linux.com registered users: We are in the process of making changes to the Linux forums. Starting Monday, 8/13/18 at 6:00 PM PT, you will be unable to access the forums. They will re-launch as soon as possible on Wednesday, 8/15/18 with new features and improved functionality. Thank you for your patience and stay tuned for the new improved forums.

July 10, 2013

Difference Between tr and sed Command


In Linux every thing is in files and some time we need to edit files to make some changes. There are many command line utilities like vim, vi, nano etc that allow us to open file, find the particular word from file and replace it with our correct word. If we want to modify a large file without opening, there are also many command line utilities as echo, sed and tr in Linux that will allow us to modify a file without opening it. Sometimes we can do same modification in a file with sed and tr. As per below example we can use sed and tr command for same purpose. Where we can use both sed or tr, we will prefer to use of tr command because the tr is more faster. Of course, in many practical cases, the speed difference is too small to notice.

Suppose we have a string as "This+is+test+for+tr+and+sed" and we want to replace '+' with white-space ' ' and this type of replacement can be done with both tr as well sed command as below

[user@test ~]$ echo This+is+test+for+tr+and+sed |tr '+' ' '
This is test for tr and sed
[user@test ~]$ echo This+is+test+for+tr+and+sed |sed 's/\+/ /g'
This is test for tr and sed

We can use sed and tr commands as editor and basic text transformations, but there are difference in uses of tr command and sed command.

Difference between tr and sed

tr command Translate, squeeze, delete characters from standard input, writing to standard output. on the other hand sed is a stream editor or it is used to perform basic text transformations on an input stream

tr perform character based transformation but sed perform string based transformation.

For example

[user@test ~]$ echo I am a good boy | tr 'good' 'test'
I am a tsst bsy

tr has done character based transformation and it is replacing good to best as g=b, o=e, o=s, d=t and because o is double so it ignore first rule and using o=s and output is as above.

[user@test ~]$ echo I am a good boy | sed 's/good/best/g'
I am a best boy

But sed is string based transformation and if there will 'good' string more than one time those will replace with 'best'.

But in other cases tr command also more useful and easier. Just suppose that we have entered braces '{}' by mistake instead of parenthesis '()' in a file test.txt and we can translate braces with parenthesis with tr.

[user@test ~]$ tr '{}' '()' < test.txt > newtest.txt

It will replace '{}' with '()' from test.txt and save output in newtest.txt.

Click Here!