How can `tr` be used to remove trailing spaces?

QuestionsQuestions8 SkillsProDec, 18 2025
0145

Actually, it is important to know that tr (translate) cannot be used to remove trailing spaces specifically.

The tr command is designed for character-by-character translation or deletion across the entire file; it does not understand context like "the end of a line."

Why tr isn't the right tool:

  • If you use tr -d ' ', it will remove all spaces in the file (turning "Daily Report" into "DailyReport").
  • tr cannot distinguish between a space in the middle of a sentence and a space at the end of a line.

How tr IS commonly used with spaces:

While it can't target just the trailing ones, tr is often used to "squeeze" multiple spaces into one:

# This turns multiple spaces into a single space everywhere
cat file.txt | tr -s ' '

Better Alternatives for Trailing Spaces:

Since tr isn't suitable, here is the standard way to do it using a command-line tool that does understand line endings:

1. Using sed (Recommended):

sed 's/ *$//' daily_report.txt

(This looks for a space followed by the end-of-line anchor $).

2. Using perl:

perl -pe 's/\s+$//' daily_report.txt

In summary: use cat -E to see them, and use sed to remove them

0 Comments

no data
Be the first to share your comment!