Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Bash Dictionary
  3. tr / col / expand

tr / col / expand

tr translates, deletes, or compresses characters one character at a time. expand converts tabs to spaces, and unexpand converts spaces to tabs. These commands are commonly used for character-level text formatting such as line ending conversion and case conversion.

Syntax

tr [options] set1 [set2]
expand [options] [file...]
unexpand [options] [file...]

Options

Command / OptionDescription
tr 'abc' 'ABC'Translates each character in set1 to the corresponding character in set2.
tr '[:lower:]' '[:upper:]'Converts all lowercase letters to uppercase.
tr '[:upper:]' '[:lower:]'Converts all uppercase letters to lowercase.
tr -d 'set'Deletes all characters in the specified set.
tr -s 'set'Squeezes consecutive repeated characters in the set into a single character.
tr -c 'set1' 'set2'Translates the complement of set1 (characters not in set1) to set2.
tr '\r' '\n'Used to remove the \r from Windows line endings (\r\n).
expand fileConverts tabs to 8 spaces.
expand -t N fileConverts tabs to N spaces.
unexpand fileConverts leading spaces to tabs.

Sample Code

The following examples demonstrate how each command works.

# Example input text:
# "hello world"       → convert to uppercase
# "my file name.txt"  → replace spaces
# "abc123def456"      → delete characters
# "too    many   spaces" → squeeze repeated characters

Converts all lowercase letters to uppercase.

echo "hello world" | tr '[:lower:]' '[:upper:]'
HELLO WORLD

Replaces spaces with underscores (useful for normalizing filenames).

echo "my file name.txt" | tr ' ' '_'
my_file_name.txt

Uses -d to delete specified characters. This example removes all alphabetic characters, leaving only digits.

echo "abc123def456" | tr -d '[:alpha:]'
123456

Uses -s to squeeze consecutive repeated characters into one.

echo "too    many   spaces" | tr -s ' '
too many spaces

Combines -s with cut to extract fields from data with irregular spacing.

echo "  alice  30  Tokyo  " | tr -s ' ' | cut -d' ' -f2-
alice 30 Tokyo

Uses -c (complement) to replace all non-alphanumeric characters with spaces.

echo "hello, world! 123" | tr -c '[:alnum:]\n' ' '
hello  world  123

Removes \r from Windows line endings (\r\n) to convert to Unix format.

tr -d '\r' < windows_file.txt > unix_file.txt

Uses expand -t N to convert tabs to N spaces.

printf "name\tage\ncity\tcode\n" | expand -t 8
name    age
city    code

Notes

tr does not accept filenames as arguments — it only reads from standard input. To process a file, redirect it using tr < file.

tr is commonly used to convert line endings when working with Windows text files on Linux (\r\n → \n). For more advanced text transformation, see also sed.

If you find any errors or copyright issues, please .