Linux将空格转换为制表符

john@ls001a:~> echo "This is a test" | tr [:space:] '\t'
This    is      a       test

删除多余的空格

john@ls001a:~> echo "This    is     for     testing" | tr -s [:space:] ' '
This is for testing

删除换行符

-d选项用于指定tr命令来删除字符。tr命令的常见用法是从文件中删除换行字符。换行字符为\n

john@ls001a:~> cat test2.txt
Line one
Line two
Line three
Line four
Line Five

john@ls001a:~> cat test2.txt | tr -d "\n"
Line oneLine twoLine threeLine fourLine Five

除了-n转义字符。您还可以指定以下任何值:

       \NNN   8进制值为NNN的字符 

       \     反斜杠

       \a     蜂鸣

       \b     backspace

       \f     表单符 

       \n     换行

       \r     回车

       \t     水平制表符,即tab

       \v     垂直制表符

删除指定字符

-d参数可用于轻松删除字符:

john@ls001a:~> echo "This is another test" | tr -d 'a'
This is nother test

在上面的示例中,字符a已删除!

tr命令示例

在以下示例中,我们使用tr命令翻译键入的文本。任何以小写字母输入的字母都将翻译为大写字母:

john@ls001a:~> tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
welcome to the it road
WELCOME TO THE IT ROAD

大写小写字符之间进行转换的一种更简单的方法是使用[:lower:][:upper:]选项:

john@ls001a:~> echo 'welcome to the it road' | tr "[:lower:]" "[:upper:]"
WELCOME TO THE IT ROAD

通过指定字符范围azAz,可以实现一种获得相同结果的流行方法。

john@ls001a:~> echo 'welcome to the it road' | tr "a-z" "A-Z"
WELCOME TO THE IT ROAD

将空格转换为换行符

john@ls001a:~> echo "This is a test" | tr [:space:] '\n'
This
is
a
test
tr命令

tr命令(翻译)用于字面翻译或删除字符。tr命令通常使用两组字符,然后将其替换为第二组字符。

翻译文件的内容

在下面的例子中,我们使用了一个名为test.txt的文件。文件内容如下图所示:

john@ls001a:~> cat test.txt
start[]
middle[]
end[]

我们使用重定向读取文本文件的内容,然后将文件的翻译版本写入名为newfile.txt的新文件中:

john@ls001a:~> tr '[]' '()' < test.txt > newfile.txt

john@ls001a:~> cat newfile.txt
start()
middle()
end()

将换行转换为单个空格

john@ls001a:~> tr -s '\n' ' ' < test2.txt
Line one Line two Line three Line four Line Five 
日期:2019-04-29 03:17:28 来源:oir作者:oir