tr
文本处理
用法
tr '[set1]' '[set2]'逐个字符地替换或删除;它只读标准输入,直接给文件名会失败,必须用 < 重定向或用管道喂给它。
常用选项
| 选项 | 含义 |
|---|---|
| -d | Delete every character in the set |
| -s | Squeeze repeats of a character into one |
| -c | Use the complement of the set |
| -cd | Delete everything that is not in the set |
示例
tr 'a-z' 'A-Z' < notes.txtUppercases everything.
tr -d '\r' < win.txt > unix.txtStrips CR, turning CRLF endings into LF.
tr -s ' ' < spaced.txtCollapses runs of spaces into one.
它们本来就是用管道串起来用的。串三条往往比让一条命令做完所有事更短。
怎么看
- 方括号 [ ] 表示这部分可以不写。
- 省略号 … 表示可以写多个。
- 选项区分大小写——有些命令里 -r 和 -R 不是一回事。
常见问题
Q. tr 是做什么的?
逐个字符地替换或删除;它只读标准输入,直接给文件名会失败,必须用 < 重定向或用管道喂给它。
Q. 怎么写?
tr '[set1]' '[set2]' —— 方括号表示可以省略的部分。
Q. 值得记的选项有几个?
这里列了 4 个,完整列表在 man tr。这条命令属于文本处理。
相关命令
man 手册: man tr