用linux中的选项卡替换空格

biz*_*nez 92 linux whitespace tabs

如何用给定文本文件中的linux中的选项卡替换空格?

Dig*_*oss 162

使用unexpand(1)程序


UNEXPAND(1)                      User Commands                     UNEXPAND(1)

NAME
       unexpand - convert spaces to tabs

SYNOPSIS
       unexpand [OPTION]... [FILE]...

DESCRIPTION
       Convert  blanks in each FILE to tabs, writing to standard output.  With
       no FILE, or when FILE is -, read standard input.

       Mandatory arguments to long options are  mandatory  for  short  options
       too.

       -a, --all
              convert all blanks, instead of just initial blanks

       --first-only
              convert only leading sequences of blanks (overrides -a)

       -t, --tabs=N
              have tabs N characters apart instead of 8 (enables -a)

       -t, --tabs=LIST
              use comma separated LIST of tab positions (enables -a)

       --help display this help and exit

       --version
              output version information and exit
. . .
STANDARDS
       The expand and unexpand utilities conform to IEEE Std 1003.1-2001
       (``POSIX.1'').
Run Code Online (Sandbox Code Playgroud)

  • 只是一个警告 - unexpand不会将单个空格转换为制表符.如果您需要盲目地将所有0x20个字符的运行转换为单个选项卡,则需要使用不同的工具. (12认同)
  • 哇,从来不知道扩展/扩展存在.我试图做相反的事情,扩展是完美的,而不是乱用`tr`或`sed`. (4认同)
  • 对于记录,expand/unexpand是[标准实用程序](http://pubs.opengroup.org/onlinepubs/009695299/utilities/unexpand.html). (4认同)
  • 太酷了,这些都是标准的.我喜欢[UNIX哲学](https://en.wikipedia.org/wiki/UNIX_philosophy).如果它可以做到,那将是很好的. (4认同)
  • 我不认为unexpand会在这里工作..它只转换前导空格,只有两个或多个空格..请看这里:http://lists.gnu.org/archive/html/bug-textutils/2001-01 /msg00025.html (3认同)
  • 无法编辑上面的评论.对我来说,`sed's /\+ /\t/g"`做了伎俩. (3认同)
  • 让“扩展”写回原始文件的最简单方法是什么?如果我尝试`expand main.cpp > main.cpp`,它会擦除​​文件。 (2认同)

Jon*_*han 41

我想你可以试试awk

awk -v OFS="\t" '$1=$1' file1
Run Code Online (Sandbox Code Playgroud)

或SED,如果你preffer

sed 's/[:blank:]+/,/g' thefile.txt > the_modified_copy.txt
Run Code Online (Sandbox Code Playgroud)

甚至是tr

tr -s '\t' < thefile.txt | tr '\t' ' ' > the_modified_copy.txt
Run Code Online (Sandbox Code Playgroud)

或Sam Bisbee提取的tr解决方案的简化版本

tr ' ' \\t < someFile > someFile
Run Code Online (Sandbox Code Playgroud)

  • 在您的sed示例中,出于效率/速度原因,最佳实践要求您使用tr替换sed上的单个字符.此外,tr示例更容易:`tr''\\ t <someFile> someFile` (3认同)
  • 当然,tr比sed具有更好的性能,但我爱Unix的主要原因是有很多方法可以做某事.如果您打算多次进行此替换,您将搜索性能良好的解决方案,但如果您只打算执行一次,您将搜索一个涉及让您感觉舒适的命令的解决方案. (2认同)
  • ARG.我不得不使用反复试验来使sed工作.我不知道为什么我必须像这样逃避加号:`ls -l | sed"s /\+// g"` (2认同)

Joh*_*kin 10

使用Perl:

perl -p -i -e 's/ /\t/g' file.txt
Run Code Online (Sandbox Code Playgroud)

  • 使用单个选项卡替换连续空格时遇到类似问题.Perl工作只使用了正则表达式的"+". (3认同)

小智 9

更好的tr命令:

tr [:blank:] \\t
Run Code Online (Sandbox Code Playgroud)

这将清除say,unzip -l的输出,以便用grep,cut等进一步处理.

例如,

unzip -l some-jars-and-textfiles.zip | tr [:blank:] \\t | cut -f 5 | grep jar
Run Code Online (Sandbox Code Playgroud)