Difference Between tr and sed Command

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.


Originally From: [http://www.linux.com/community/forums/command-line/difference-between-tr-and-sed-command/layout/default]




tr Command
-c Complement
-s Squeeze Repeate

You can complement the SET1 using -c option. For example, to remove all characters except digits, you can use the following.

$ echo “my username is 432234” | tr -cd [:digit:]



remove all the double quotes in the file.

head -10 test | tr -d “\””
tr -d \” < test


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s