我很少用tr命令,这里记录一下简单的用法,以利于未来用到时快速查阅。
从man tr可以得到以下信息
tr的语法是: stdin | tr [选项] 字符集合1 字符集合2。一般,字符集合1和字符集合2是映射关系,当二者不是一一对应映射的时候,会出现字符丢失的情况。当使用-d选项时,只用字符集合1,不用字符集合2。
例子1: 删除操作(使用-d选项)
# 把在stdin里找到的全部数字都删掉,然后输出stdout root@hgdm:~# echo '1900 The best way out is always through 2000'| tr -d '0-9'The best way outisalways through
例子2: 替换操作(不使用任何选项)
# 把在stdin里的找到的全部小写字母转换(替换)为大写字母,然后输出到stdoutroot@hgdm:~# echo 'The best way out is always through'| tr 'a-z''A-Z'THE BEST WAY OUT IS ALWAYS THROUGH root@hgdm:~# echo 'The best way out is always through'| tr [:lower:] [:upper:] THE BEST WAY OUT IS ALWAYS THROUGH # 把在stdin里的找到的全部数字转换(替换)为空格,然后输出到stdoutroot@hgdm:~# echo '1900 The best way out is always through 2000'| tr '0-9'' 'The best way out is always through
例子3: 压缩操作(使用-s选项)
# 将stdin里找到的多个连续a压缩为一个aroot@hgdm:~# echo 'aaabbb,aaabbb,aaabbb,aaabbb' | tr -s 'a'abbb,abbb,abbb,abbb # 将stdin里找到的多个连续空格压缩为一个空格root@hgdm:~# echo ' The best way out is always through ' | tr -s ' 'The best way out is always through
下面示例将多个连续的换行符压缩为一个换行符
root@hgdm:~/examples# cat blanks.txt the best way out is always through root@hgdm:~/examples# cat blanks.txt | tr -s '\n'the best way out is always through
清除stdin里的空白行
例子4: 补集(使用-c选项)
# -c '0-9'指非数字集合: '0-9'是数字集合,数字集合的补集是非数字集合# -c [:digit:]指非数集合: [:digit:]是数字集合,数字集合的补集是非数字集合# -d -c '0-9'和-d -c [:digit:]: 用于删除stdin里的非数字,字母、空格、换行符、标点符号等都属于非数字,都会被删除root@hgdm:~# echo '1900 The best way out is always through 2000 ,#@^&&**&' | tr -d -c '0-9'19002000root@hgdm:~# echo '1900 The best way out is always through 2000 ,#@^&&**&' | tr -d -c [:digit:]19002000
PHP里有一个类似tr命令的函数strtr()
例如,
<?php$inputStr = '伟大,渺小;真诚,虚伪;尊重,歧视;善良,邪恶。'; $searchList = ['渺小', '虚伪', '歧视', '邪恶']; $replaceList = array_fill(0, count($searchList), '*'); $trans = array_combine($searchList, $replaceList); $outputStr = strtr($inputStr, $trans); print_r([ 'inputStr'=> $inputStr, 'searchList'=> $searchList, 'replaceList'=> $replaceList, 'trans'=> $trans, 'outputStr'=> $outputStr ]); echo$outputStr . "\n";
这段代码的输出结果为:
PHP strtr()函数