2019-04-08 23:22:26 +08:00

58 lines
3.0 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<h1 id="tr">tr</h1>
<p>将字符进行替换压缩和删除</p>
<h2 id="补充说明">补充说明</h2>
<p><strong>tr命令</strong> 可以对来自标准输入的字符进行替换、压缩和删除。它可以将一组字符变成另一组字符,经常用来编写优美的单行命令,作用很强大。</p>
<h3 id="语法">语法</h3>
<pre><code>tr(选项)(参数)</code></pre>
<h3 id="选项">选项</h3>
<pre><code>-c或——complerment取代所有不属于第一字符集的字符
-d或——delete删除所有属于第一字符集的字符
-s或--squeeze-repeats把连续重复的字符以单独一个字符表示
-t或--truncate-set1先删除第一字符集较第二字符集多出的字符。</code></pre>
<h3 id="参数">参数</h3>
<ul>
<li>字符集1指定要转换或删除的原字符集。当执行转换操作时必须使用参数“字符集2”指定转换的目标字符集。但执行删除操作时不需要参数“字符集2”</li>
<li>字符集2指定要转换成的目标字符集。</li>
</ul>
<h3 id="实例">实例</h3>
<p>将输入字符由大写转换为小写:</p>
<pre><code>echo &quot;HELLO WORLD&quot; | tr &#39;A-Z&#39; &#39;a-z&#39;
hello world
</code></pre>
<p>A-Za-z都是集合集合是可以自己制定的例如ABD-}bB.,a-de-ha-c0-9都属于集合集合里可以使用可以可以使用其他ASCII字符。</p>
<p>使用tr删除字符</p>
<pre><code>echo &quot;hello 123 world 456&quot; | tr -d &#39;0-9&#39;
hello world </code></pre>
<p>将制表符转换为空格:</p>
<pre><code>cat text | tr &#39;\t&#39; &#39; &#39;</code></pre>
<p>字符集补集,从输入文本中将不在补集中的所有字符删除:</p>
<pre><code>echo aa.,a 1 b#$bb 2 c*/cc 3 ddd 4 | tr -d -c &#39;0-9 \n&#39;
1 2 3 4
</code></pre>
<p>此例中补集中包含了数字0~9、空格和换行符所以没有被删除其他字符全部被删除了。</p>
<p>用tr压缩字符可以压缩输入中重复的字符</p>
<pre><code>echo &quot;thissss is a text linnnnnnne.&quot; | tr -s &#39; sn&#39;
this is a text line.</code></pre>
<p>巧妙使用tr做数字相加操作</p>
<pre><code>echo 1 2 3 4 5 6 7 8 9 | xargs -n1 | echo $[ $(tr &#39;\n&#39; &#39;+&#39;) 0 ]
</code></pre>
<p>删除Windows文件“造成”的^M字符</p>
<pre><code>cat file | tr -s &quot;\r&quot; &quot;\n&quot; &gt; new_file
cat file | tr -d &quot;\r&quot; &gt; new_file</code></pre>
<p><strong>tr可以使用的字符类</strong></p>
<pre><code>[:alnum:]:字母和数字
[:alpha:]:字母
[:cntrl:]:控制(非打印)字符
[:digit:]:数字
[:graph:]:图形字符
[:lower:]:小写字母
[:print:]:可打印字符
[:punct:]:标点符号
[:space:]:空白字符
[:upper:]:大写字母
[:xdigit:]:十六进制字符 </code></pre>
<p>使用方式:</p>
<pre><code>tr &#39;[:lower:]&#39; &#39;[:upper:]&#39;</code></pre>
<!-- Linux命令行搜索引擎https://jaywcjlove.github.io/linux-command/ -->