tr vs sed: String Manipulation in Linux

tr vs sed: String Manipulation in Linux

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