find命令输出的自定义排序

时间:2013-01-29 12:50:59

标签: python bash

我正在尝试使用unix“find”命令获取已排序的目录/文件列表。

# find . -type f 
.
./bin
./data
./data/disks
./inc
./inc/calls
./inc/calls/show
./inc/calls/show/system
./inc/calls/show/cli
./inc/calls/show/network
./inc/calls/show/stats
./inc/calls/services
./inc/calls/services/ntp
./inc/calls/services/tsa
./inc/calls/services/webgui
./inc/calls/services/engine
./inc/calls/system
./inc/calls/change
./inc/calls/change/password
./inc/calls/change/network
./inc/calls/disk
./inc/calls/disk/encr
./inc/etc

我想把它整理成:

./inc/calls/show/system \    
./inc/calls/show/cli \
./inc/calls/show/network \
./inc/calls/show/stats \
./inc/calls/services/ntp \
./inc/calls/services/tsa \
./inc/calls/services/webgui \
./inc/calls/services/engine \
./inc/calls/change/password \
./inc/calls/change/network \
./inc/calls/disk/encr \
./inc/calls/system \
./inc/calls/change \
./inc/calls/services \
./inc/calls/disk \
./inc/calls/show \
./inc/calls \
./data/disks \
./inc/etc \
./bin \
./data \
./inc

哪个节点(目录/文件)有更多的子(目录/文件)应该是第一个...我想用bash或python做... ...最好的方法是什么?

2 个答案:

答案 0 :(得分:1)

匹配包含/的行,并使用/作为分隔符将字段数添加到该行,对字段数进行排序并删除计数。

$ awk -F/ '/\//{print NF,$0}' file | sort -nrk1 | cut -d' ' -f2-
./inc/calls/show/system
./inc/calls/show/stats
./inc/calls/show/network
./inc/calls/show/cli
./inc/calls/services/webgui
./inc/calls/services/tsa
./inc/calls/services/ntp
./inc/calls/services/engine
./inc/calls/disk/encr
./inc/calls/change/password
./inc/calls/change/network
./inc/calls/system
./inc/calls/show
./inc/calls/services
./inc/calls/disk
./inc/calls/change
./inc/etc
./inc/calls
./data/disks
./inc
./data
./bin

答案 1 :(得分:0)

我会使用python并尝试转换:

a/b
a/c
b/e/f
b/e/g

之类的:

{'a': {'b': {}, 'c': {}},
'b': {'e': {'f': {}, 'g': {}}},
} 

实现这一目标:

def add_list_to_dict(lst,d):
   key, lst = lst[0], lst[1:]
   if not key in d:
       d[key] = {}
   if lst:
       add_list_to_dict(lst,d[key])

d = {}
for path in paths:
    add_list_to_dict(path.split('/'),d)