在正则表达式中将空格转换为制表符

5
如何在正则表达式中表示以下内容:
foreach line
   look at the beginning of the string and convert every group of 3 spaces to a tab
   Stop once a character other than a space is found

这是我目前的进展:

这是我目前的进展:

/^ +/\t/g

然而,这会将每个空格都转换为1个制表符。欢迎提供任何帮助。

1
请发布您已经编写的代码。人们通常不喜欢只为您编写代码。 - Mitch Wheat
3个回答

9

使用Perl:

perl -pe '1 while s/\G {3}/\t/gc' input.txt >output.txt

例如,有以下输入:
nada
   three spaces
    four spaces
   three   in the middle
      six space

输出结果(TAB用\t替换)如下:
$ perl -pe '1 while s/\G {3}/\t/gc' input | perl -pe 's/\t/\\t/g'
nada
\tthree spaces
\t four spaces
\tthree   in the middle
\t\tsix spaces

1
Greg,感谢你的出色回答!然而,它似乎过于复杂了。1 while//c都似乎是多余的。为了确保,我尝试运行了您的示例输入,并保留/省略这两个多余的项目的所有排列组合,结果输出相同。因此,可以通过只使用perl -pe 's/\G {3}/\t/g'来简化代码。 - Noach Magedman

4

我知道这是一个老问题,但我想提供一个完整的正则表达式答案,它可以工作(至少对我而言有效)。

s/^\t* {3}/\t/g

2
转换行中的空格,违反“一旦发现除空格以外的字符就停止”的规则。 - Noach Magedman

-1

你可能想要 /^(?: {3})*/\t/g

编辑:已修复


这将3个空格转换成1个制表符 - 但也将6或9或12等等的空格转换为仅1个制表符。 - Tim Pietzcker
尝试在Greg Bacon的示例数据上运行它。 "nada"和"six spaces"都无法正常工作。而且缺少前导s - Noach Magedman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接