tags:

views:

172

answers:

3

How do do you say the following in regex:

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

This is what i have so far:

/^ +/\t/g

However, this converts every space to 1 tab

Any help would be appreciated.

+3  A: 

With Perl:

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

For example, with the following input

nada
   three spaces
    four spaces
   three   in the middle
      six space

the output (TABs replaced by \t) is

$ 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
Greg Bacon
+1  A: 

You probably want /^(?: {3})*/\t/g

edit: fixed

jonchang
This converts 3 spaces to 1 tab - but also 6 or 9 or 12 etc. spaces to only 1 tab.
Tim Pietzcker
A: 

Perl, sed, ruby, ...

s/^   /\t/

That is a caret (^) followed by three spaces.

Levi