tr命令用来translate,squeeze or delete characters。tr是translate的意思。tr从STDIN读取输入,写到STDOUT。
语法
$ tr [OPTION] SET1 [SET2]
如果指定了SET1和SET2,且没有指定-d选项。SET1中的字符被SET2中同位置的字符替换。
例如,转换小写为大写
$ tr [:lower:] [:upper:]
-s, --squeeze-repeats
最后一个SET中的字符,如果有多个连续,则替换成一个。
把多个空格挤压成一个空格
1 2 3 | $ tr -s ' ' a b a b |
可以先translate,然后squeeze。
1 2 3 | $ tr -s A a bAAAAAAAc bac |
-d, --delete
删除SET1中的字符
1 2 3 | $ tr -d a abc bc |
-c, -C, --complement
使用SET的补集而不是SET本身
例如,删除所有的非数字:
1 2 3 | $ tr -C -d [:digit:] a1b2c3 123$ |
注意,换行符也被删除,所以输入a1b2c3后按回车,然后按^D,如果按^C则缓存不会输出,程序就退出了。
SET2应该和SET1的长度一样,如果SET2比SET1短,那么SET2会重复SET2的最后一个字符,和SET1一样长。如果SET2比SET1长,那么SET2被阶段。
比如 tr "abc" "d",实际上是把abc都替换成d。
-t, --truncate-set1 选项,则把SET1截断成和SET2一样。
有很多特殊字符是没办法直接表示的,因此SET有下面的表示方法。
\NNN character with octal value NNN (1 to 3 octal digits)
\\ backslash
\a audible BEL
\b backspace
\f form feed
\n new line
\r return
\t horizontal tab
\v vertical tab
CHAR1-CHAR2
all characters from CHAR1 to CHAR2 in ascending order
[CHAR*]
in SET2, copies of CHAR until length of SET1
[CHAR*REPEAT]
REPEAT copies of CHAR, REPEAT octal if starting with 0
[:alnum:]
all letters and digits
[:alpha:]
all letters
[:blank:]
all horizontal whitespace
[:cntrl:]
all control characters
[:digit:]
all digits
[:graph:]
all printable characters, not including space
[:lower:]
all lower case letters
[:print:]
all printable characters, including space
[:punct:]
all punctuation characters
[:space:]
all horizontal or vertical whitespace
[:upper:]
all upper case letters
[:xdigit:]
all hexadecimal digits
[=CHAR=]
all characters which are equivalent to CHAR
参考
https://www.thegeekstuff.com/2012/12/linux-tr-command
https://www.putorius.net/linux-tr-command.html#using-the-tr-command-truncate-option