0%

Shell tr 命令解释

version

1
2
3
4
5
6
7
8
$ tr --version
tr (GNU coreutils) 8.4
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Jim Meyering.

SYNOPSIS

1
tr [OPTION]... SET1 [SET2]

DESCRIPTION

(并非完全翻译 man,而是根据自己理解适当整理)

用于连续相同字符的压缩、字符删除、字符替换,从标准输入读入,并写入标准输出

  • 与grep、sed、awk等以文件行为操作单位不同,tr 命令以字符为操作单位
  • 命令的读写,需要重定向操作符
    1
    tr 'abc' 'ABC' < input > output

Options

default

什么参数也不带,默认是字符替换

1
2
3
# set1 中的字符被依次替换为 set2 中的字符。   
$ echo "abc" | tr 'abc' 'ABC'
ABC

若 set1 中字符比 set2 中字符多如何?会用最后一个 set2中的字符替换所有 set1 中bi set2 多出来的字符

1
2
$ echo "abc" | tr 'abc' 'AB'
ABB

-t

1
2
-t, --truncate-set1
first truncate SET1 to length of SET2

接着上例,若想,set1 比 set2 多出来的部分,直接丢弃,不用 set2 最后一个字符替换。则用 -t 参数

1
2
$ echo "abc" | tr -t 'abc' 'AB'
ABc

-c

1
2
-c, -C, --complement
use the complement of SET1

取 set1 的补集

1
2
3
4
5
6
7
# 替换 set1 中的字符
$ echo "abcd" | tr 'abc' 'AB'
ABBd

# 替换所有非 set1中的字符
$ echo "abcd" | tr -c 'abc' 'AB'
abcBB[xxx@xxx]$

此时的替换对象无法一一对应,均会替换为 set2 中的最后一个字符
注:由于默认 echo 默认会在字符串结尾加入换行符,取反替换后,换行符也被替换

-s

1
2
-s, --squeeze-repeats
replace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that character

将 set1 中每个字符串的连续重复字串,用一个字符串替换,这种模式不需要 set2 操作数

1
2
$ echo 'aaa  ccc' | tr -s 'abc'
a c

连续的 a,c被替换成了一个 a,c

-d

1
2
-d, --delete
delete characters in SET1, do not translate

删除 set1 中出现的字符,此时也不需要 set2 操作数

1
2
$ echo 'abc' | tr -d 'ac'
b

交叉使用

-c and -s
1
2
3
4
5
6
# 压缩重复的a,c字符
$ echo 'aaabbbccc' | tr -s 'ac'
abbbc
# 压缩重复的 非a,c字符
$ echo 'aaabbbccc' | tr -s -c 'ac'
aaabccc
-c and -d
1
2
3
4
5
6
# 删除 a,c字符
$ echo 'aaabbbccc' | tr -d 'ac'
bbb
# 删除非 a,c字符
$ echo 'aaabbbccc' | tr -d -c 'ac'
aaaccc[xxx@xxx]$

注:末尾的换行符也被替换了

Over

本篇只介绍具体参数用法,至于

1
2
3
4
5
6
7
8
9
10
11
12
13
14
...
\\ backslash
\a audible BEL
\b backspace
...
[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
...

与其他命令所用的范围配置均类似,此处不做介绍