expand和unexpand命令

时间:2019-04-29 03:17:28  来源:igfitidea点击:

使用expand和unexpand命令将空格转换为Tabs,将Tabs转换为空格。

expand指令

expand命令用于将文件中的制表符转换为空格。如果没有传递文件或传递了-,则将读取标准输入。

命令的基本语法:expand [OPTION] ... [FILE] ...

下面的示例中将使用以下文本文件file1file1的内容在每个字段之间包含了tab。可以使用cat -vet选项显示隐藏的字符来验证这一点。

john@john-desktop:~/test$ cat file1
One	Two	Three	Four	Five	six	seven
One	Two	Three	Four	Five	six	seven
One	Two	Three	Four	Five	six	seven
One	Two	Three	Four	Five	six	seven
One	Two	Three	Four	Five	six	seven
One	Two	Three	Four	Five	six	seven
One	Two	Three	Four	Five	six	seven
One	Two	Three	Four	Five	six	seven

john@john-desktop:~/test$ cat -vet file1
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$

通过对file1使用cat -vet选项,我们可以看到选项卡由I ^字符表示。$表示换行符。现在,如果使用expand命令,则可以将这些选项卡转换为空格。我们将使用expand命令并创建一个名为file2的新文件。

john@john-desktop:~/test$ expand file1 > file2
john@john-desktop:~/test$ cat -vet file2
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$

unexpand命令

unexpand命令用于将空格字符(空白)转换为每个文件中的选项卡。

命令的基本语法:unexpand [OPTION] ... [FILE] ...

下面是使用我们先前创建的文件file2的示例。从cat -vet命令,我们可以看到file2中没有选项卡。现在,我们将使用unexpand命令将它们转换为制表符,然后创建一个名为file3的新文件。

john@john-desktop:~/test$ cat -vet file2
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
One     Two     Three   Four    Five    six     seven$
john@john-desktop:~/test$ unexpand -a file2 > file3
john@john-desktop:~/test$ cat -vet file3
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$
One^ITwo^IThree^IFour^IFive^Isix^Iseven$