Solução estendida Python
:
Amostra infile
contents (4 levels):
first
apple
orange
train
car
truck
automobile
kiwi
third
orange
apple
plane
second
lemon
Script sort_hierarchy.py
:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import re
with open(sys.argv[1], 'rt') as f:
pat = re.compile(r'^\s+')
paths = []
for line in f:
offset = pat.match(line)
item = line.strip()
if not offset:
offset = 0
paths.append(item)
else:
offset = offset.span()[1]
if offset > prev_offset:
paths.append(paths[-1] + '.' + item)
else:
cut_pos = -prev_offset//offset
paths.append('.'.join(paths[-1].split('.')[:cut_pos]) + '.' + item)
prev_offset = offset
paths.sort()
sub_pat = re.compile(r'[^.]+\.')
for i in paths:
print(sub_pat.sub(' ' * 4, i))
Uso:
python sort_hierarchy.py path/to/infile
A saída:
first
apple
kiwi
orange
car
automobile
truck
train
second
lemon
third
apple
plane
orange