← 返回命令列表

Linux command

tr 命令

文本

涉及管道、覆盖或删除,执行前请先确认路径和参数。

常用示例

Translate characters

echo "hello" | tr 'a-z' 'A-Z'

Delete specific characters

echo "hello 123" | tr -d '0-9'

Squeeze repeated characters

echo "helllo" | tr -s 'l'

Replace newlines with spaces

tr '\n' ' ' < [file]

Delete non-printable characters

tr -cd '[:print:]' < [file]

Translate spaces to tabs

tr ' ' '\t' < [file]

Delete all except specified characters

echo "hello123" | tr -cd '0-9'

说明

tr translates, deletes, or squeezes characters from standard input, writing to standard output. It operates character-by-character, making it efficient for simple transformations. Translation replaces each character in set1 with the corresponding character in set2. If set2 is shorter, its last character is repeated. If longer, excess characters are ignored. With -d, characters in set1 are deleted. With -s, repeated characters in set1 are squeezed to single occurrences. Both can be combined. -c complements set1, meaning "all characters NOT in set1." Useful for keeping only specific characters.

参数

-d, --delete
Delete characters in set1
-s, --squeeze-repeats
Replace repeated characters with single occurrence
-c, -C, --complement
Use complement of set1
-t, --truncate-set1
Truncate set1 to length of set2

FAQ

What is the tr command used for?

tr translates, deletes, or squeezes characters from standard input, writing to standard output. It operates character-by-character, making it efficient for simple transformations. Translation replaces each character in set1 with the corresponding character in set2. If set2 is shorter, its last character is repeated. If longer, excess characters are ignored. With -d, characters in set1 are deleted. With -s, repeated characters in set1 are squeezed to single occurrences. Both can be combined. -c complements set1, meaning "all characters NOT in set1." Useful for keeping only specific characters.

How do I run a basic tr example?

Run `echo "hello" | tr 'a-z' 'A-Z'` in a terminal, then adjust file names, paths, flags, or remote targets for your system.

What does -d, --delete do in tr?

Delete characters in set1