GekBuzz

Answers, Explainers & Everyday Guides

10 Essential tr Command Examples in Linux You Should Know

10 Essential tr Command Examples in Linux You Should Know

The tr command in Linux is a powerful utility used for translating or deleting characters from input data. Whether you’re a beginner learning shell scripting or an experienced sysadmin automating text processing tasks, mastering tr can greatly simplify your workflows. This list covers 10 practical examples demonstrating how to use tr effectively in various scenarios.

1. Convert Lowercase to Uppercase

This is one of the most common uses of tr. By specifying the ranges a-z and A-Z, you can quickly convert all lowercase letters in a stream or file to uppercase. For example, echo "hello world" | tr 'a-z' 'A-Z' outputs HELLO WORLD. This is useful for standardizing text input or preparing data for case-insensitive comparisons.

2. Replace Spaces with Tabs

Replacing spaces with tabs can help format text output or prepare data for tab-delimited processing. Using tr ' ' '\t' converts every space character to a tab. For example, echo "one two three" | tr ' ' '\t' results in one two three. This is helpful when converting space-separated values into tab-separated ones.

3. Delete All Digits From Input

The -d option deletes specified characters. To remove digits, use tr -d '0-9'. For instance, echo "user1234data567" | tr -d '0-9' outputs userdata. This is valuable when you want to clean strings by stripping out numbers.

4. Squeeze Repeated Characters

The -s option replaces repeated sequences of the same character with a single instance. For example, echo "hellooo world" | tr -s ' o' compresses multiple spaces and ‘o’s into one, outputting helo world. This is useful for normalizing whitespace or repeated characters in logs or text files.

5. Replace Newlines with Spaces

Sometimes you need to convert multiline input into a single line. Using tr '\n' ' ' replaces newline characters with spaces. For example, printf "line1\nline2\nline3" | tr '\n' ' ' outputs line1 line2 line3 . This can assist in formatting output for easier reading or further processing.

6. Remove Non-Printable Characters

By combining tr with character classes, you can strip out non-printable or control characters. For example, tr -cd '[:print:]\n' deletes all characters except printable ones and newlines. This is handy for cleaning corrupted files or sanitizing input data.

7. Map Multiple Characters to One

You can map several characters to a single character using tr. For example, echo "apple,banana;cherry" | tr ',;' ':' replaces commas and semicolons with colons, resulting in apple:banana:cherry. This is useful when normalizing delimiters in data files.

8. Convert Tabs to Spaces

The reverse of example 2, converting tabs to spaces, helps when working with text editors or scripts that require spaces. Use tr '\t' ' '. For instance, echo -e "one\ttwo\tthree" | tr '\t' ' ' outputs one two three. This is practical for preparing data for programs that don’t handle tabs well.

9. Remove Duplicate Lines Using tr and sort

While tr alone can’t remove duplicate lines, it can be combined with commands like sort and uniq for text processing. For example, cat file.txt | tr -s '\n' | sort | uniq squeezes newlines, sorts, and filters unique lines. This pipeline is useful in cleaning and deduplicating data files.

10. Convert Carriage Returns to Newlines (DOS to UNIX)

Windows text files use carriage return and newline (\r\n) endings, which can cause issues on UNIX systems. Use tr -d '\r' to delete carriage returns: cat file_dos.txt | tr -d '\r' > file_unix.txt. This is essential for cross-platform text file compatibility.

How to Choose

Choosing the right tr usage depends on your specific text manipulation needs. If you need simple character translation, such as case conversion or delimiter replacement, direct mapping with tr is efficient. For removing unwanted characters, the -d option is key. When normalizing repeated characters, -s is your tool. Remember, tr works on single characters, not strings, so for complex patterns, consider tools like sed or awk. Also, keep in mind that tr reads from standard input and writes to standard output, making it ideal for use in pipelines.

Frequently Asked Questions

Q: Can tr handle multibyte characters like UTF-8?
No, tr operates on single-byte characters and is not UTF-8 aware. For multibyte character processing, tools like iconv or awk with locale support are recommended.

Q: How does tr differ from sed or awk?
tr is specifically designed for character-level translation or deletion, working efficiently on streams. sed and awk are more powerful for pattern matching and complex text transformations.

Q: Can I use tr to replace strings or multiple characters at once?
tr only works with individual characters, so you cannot replace strings. For string replacements, use sed or perl.

Q: What happens if the sets in tr have different lengths?
If the first set is longer, the last character of the second set is used to replace all remaining characters. This can lead to unexpected results, so always ensure sets are equal length or understand the behavior.

Q: Is tr case-sensitive?
Yes, tr treats uppercase and lowercase characters distinctly unless you explicitly map them together.

Final Thoughts

Mastering the tr command unlocks efficient text manipulation capabilities in Linux. Its simplicity and speed make it ideal for quick character translations, deletions, and formatting tasks within scripts and pipelines. While limited to single-character operations, pairing tr with other tools like sed, awk, and sort can handle complex data processing needs. Experiment with these examples to enhance your command-line proficiency and streamline your text processing workflows.

Related

10 Essential tr Command Examples in Linux You Should Know

Leave a Reply

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

Scroll to top