0
0
Linux CLIscripting~10 mins

tr (translate characters) in Linux CLI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - tr (translate characters)
Input text stream
tr command reads characters
Check each character
If char in set1?
NoOutput char unchanged
Yes
Replace with corresponding char in set2
Output translated char
Repeat for all chars
End of input stream
The tr command reads input characters one by one, replaces characters found in the first set with corresponding characters from the second set, and outputs the result.
Execution Sample
Linux CLI
echo "hello" | tr "hel" "HEl"
This command replaces 'h' with 'H', 'e' with 'E', and 'l' with 'l' (unchanged) in the word 'hello'.
Execution Table
StepInput CharIs in set1?ActionOutput Char
1hYesReplace with 'H'H
2eYesReplace with 'E'E
3lYesReplace with 'l'l
4lYesReplace with 'l'l
5oNoOutput unchangedo
6End of input---
💡 Reached end of input stream, translation complete.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
Current Char-helloEnd
Output Stream"""H""HE""HEl""HEll""HEllo""HEllo"
Key Moments - 2 Insights
Why does 'l' remain lowercase in the output even though it is in the first set?
Because the corresponding character in the second set for 'l' is also 'l', so it replaces 'l' with 'l' unchanged, as shown in steps 3 and 4 in the execution_table.
What happens to characters not in the first set?
They are output unchanged, as seen with 'o' in step 5 of the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output character at step 2?
AE
Be
CH
Dl
💡 Hint
Check the 'Output Char' column at step 2 in the execution_table.
At which step does the input character 'o' get processed?
AStep 3
BStep 5
CStep 4
DStep 6
💡 Hint
Look for 'o' in the 'Input Char' column in the execution_table.
If the second set was "HEL" instead of "HEl", what would be the output character at step 3?
Al
BE
CL
DH
💡 Hint
Compare the second set characters and see what replaces 'l' at step 3.
Concept Snapshot
tr command syntax: tr SET1 SET2
Reads input characters one by one.
If character is in SET1, replace with corresponding char in SET2.
If not, output character unchanged.
Useful for simple character substitutions in streams.
Full Transcript
The tr command reads each character from the input stream. It checks if the character is in the first set (SET1). If yes, it replaces it with the corresponding character from the second set (SET2). If not, it outputs the character unchanged. This process repeats until the end of the input stream. For example, echo "hello" | tr "hel" "HEl" replaces 'h' with 'H', 'e' with 'E', and 'l' with 'l' (unchanged), resulting in 'HEllo'.