Linux 管理员 - tr 命令
以下是 tr 的语法。此命令翻译或删除字符。
tr [OPTION] SET1 [SET2]
以下是 tr 的常用开关和字符类。
命令 | 操作 |
---|---|
-d | 删除 |
-s | 压缩 SET1 中的重复文本,并在 SET2 中出现一次 |
[:alnum:] | 字母数字字符 |
[:alpha:] | 所有字母 |
[:digit:] | 所有数字 |
[:blank:] | 所有水平空格 |
[:space:] | 所有水平或垂直空格 |
[:graph:] | 所有可打印字符,不包括空格 |
[:print:] | 所有可打印字符,包括空格 |
[:punct:] | 所有标点符号 |
[:lower:] | 所有小写字符 |
[:upper:] | 所有大写字符 |
tr 通常用于翻译或删除字符串中的字符。将 tr 视为 sed 替代命令的更简单替代方案。从 stdin 读取,而不是从文件读取。
当考虑应该使用"使用 sed"还是"使用 tr"时,最好遵循保持简单的理念。如果 tr 中的操作很简单,请使用它。但是,一旦您开始考虑以递归方式使用 tr,最好使用 sed 的替换命令。
通常,tr 会将 [SET1] 替换为 [SET2] 中的字符,除非使用 -d 开关。然后,将删除 [SET1] 中流中的字符。
在我们的 names.txt 文件上使用 tr 将所有小写字符转换为大写 −
[root@centosLocal Documents]# tr [:lower:] [:upper:] < names.txt TED:DANIEL:101 JENNY:COLON:608 DANA:MAXWELL:602 MARIAN:LITTLE:903 BOBBIE:CHAPMAN:403 NICOLAS:SINGLETON:203 DALE:BARTON:901 AARON:DENNIS:305 SANTOS:ANDREWS:504 JACQUELINE:NEAL:102 [root@centosLocal Documents]#
让我们将":"字符重新转换为 Tab −
[root@centosLocal Documents]# tr [:] [\t] < names.txt Ted Daniel 101 Jenny Colon 608 Dana Maxwell 602 Marian Little 903 Bobbie Chapman 403 Nicolas Singleton 203 Dale Barton 901 Aaron Dennis 305 Santos Andrews 504 Jacqueline Neal 102 [root@centosLocal Documents]#
如果想保存结果怎么办?使用重定向非常简单。
[root@centosLocal Documents]# tr [:] [\t] < names.txt >> tabbedNames.txt [root@centosLocal Documents]# cat tabbedNames.txt Ted Daniel 101 Jenny Colon 608 Dana Maxwell 602 Marian Little 903 Bobbie Chapman 403 Nicolas Singleton 203 [root@centosLocal Documents]#
让我们对格式不佳的文本使用 -s 或挤压选项 −
[root@centosLocal Documents]# cat lines.txt line 1 line 2 line 3 line 4 line 5 [root@centosLocal Documents]# tr -s [:blank:] ' ' < lines.txt >> linesFormat.txt [root@centosLocal Documents]# cat linesFormat.txt line 1 line 2 line 3 line 4 line 5 [root@centosLocal Documents]#
basic_centos_linux_commands.html