6

I need to convert whitespace to a tiered, numbered list and have found this elusive.

This is the sort of thing I'm after:

Input (visible):

    Project #1
         Subproject
              Task
    Project #2
         Subproject
              Task
              Task

Input (raw):

\tProject #1
\t\tSubproject
\t\t\tTask
\tProject #2
\t\tSubproject
\t\t\tTask
\t\t\tTask

Desired Output:

1: Project #1
     1.1: Subproject
          1.1.1: Task
2: Project #2
     2.1: Subproject
          2.1.1: Task
          2.1.2: Task
7

Perl to the rescue!

perl -pe 'if (s/^\t(\t*)//) {
              $n[ length $1 ]++;
              splice @n, 1 + length $1;
          }
          print $1, join(".", @n), ": " ' -- file
  • s/^\t(\t+)// removes the leading tabs, but captures them (without the first one) into $1.
  • The @n array is used to keep the numbers. The number corresponding to the current depth is incremented by ++, and the rest of the numbers are removed (in case you're starting a new, less nested section).
0

Solution (could be slightly optimized):

$ cat file | perl -pe 's/^/\t/' | perl -pe 'if (s/^(\t+)//) {
              $n[length($1)-1]++;
              splice @n, length $1;
          }
          print $1, join(".", @n), ": " ' | perl -pe 's/^\t//'


1: Project #1
    1.1: Subproject
        1.1.1: Task
2: Project #2
    2.1: Subproject
        2.1.1: Task
        2.1.2: Task
3: 
  • -1, please note that you already got optimized answer above – αғsнιη May 24 at 16:48
  • @roaima It's not a starting point form OP, it's a derived version of choroba's answer but to adding an extra Tab to everyline, format it, then remove that single added Tabs at start of lines, because OP given input(raw) was different than with what visible input was (see the edit I did on OP's visible input). so I see it's not a different solution but lack of giving exact sample input by OP. – αғsнιη May 24 at 17:37
  • Oh ok thanks... – roaima May 24 at 17:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.