tr vs sed – String manipulation commands in Linux/Unix

Overview

tr and sed are very powerful stream and character manipulation commands, Each has its own advantage with string manipulation.

tr vs sed - String manipulation commands in Linux/Unix
 

tr vs sed usage and examples

Replace “hi” with “bye”

echo "hi hi" | sed 's/hi/bye/g'
output: bye bye
echo "hi hi" | tr 'hi' 'bye'
output: by by

While sed can replace strings tr can only replace characters,
so with complete string replacement sed is the way to go.
 
Replace “good” with “bad”

echo "good good" | sed 's/good/bad/g'
output: bad bad
echo "good good" | tr 'good' 'bad'
output: bddd bddd

tr is more like a mapping command, it’s like a set of rules:
The char “g=b”, the char “o=a”,”o=d” the last one will be the active one “o=d”.
 
Change ‘ ‘ to a new line:

echo "line1 line2" | tr ' ' '\n'
output:
line1
line1
echo "line1 line2" |sed -e 's/\s\s*/\n/g'
output:
line1
line1

 
As you can see tr is a lot easier for this job.
 
 
Enjoy.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.