gpt4 book ai didi

unix - 将类似 `find`的输出转换为类似 `tree`的输出

转载 作者:行者123 更新时间:2023-12-05 00:39:39 24 4
gpt4 key购买 nike

该问题是Output of ZipArchive() in tree format问题的广义版本。

在我浪费时间编写此(* nix命令行)实用程序之前,最好先弄清是否有人已经编写了该实用程序。我想要一个实用程序,它将作为其标准输入获得一个列表,例如find(1)返回的列表,并输出类似于tree(1)的列表

例如。:

输入:

/fruit/apple/green
/fruit/apple/red
/fruit/apple/yellow
/fruit/banana/green
/fruit/banana/yellow
/fruit/orange/green
/fruit/orange/orange
/i_want_my_mommy
/person/men/bob
/person/men/david
/person/women/eve

输出
/
|-- fruit/
| |-- apple/
| | |-- green
| | |-- red
| | `-- yellow
| |-- banana/
| | |-- green
| | `-- yellow
| `-- orange/
| |-- green
| `-- orange
|-- i_want_my_mommy
`-- person/
|-- men/
| |-- bob
| `-- david
`-- women/
`-- eve

用法应类似于:
list2tree --delimiter="/" < Input > Output

Edit0:看来我不清楚此练习的目的。我喜欢tree的输出,但我希望将其用于任意输入。它可能不属于任何文件系统 namespace 。

Edit1:修复了输出中的 person分支。谢谢,@ Alnitak。

最佳答案

我整理了一个Perl脚本,该脚本分割路径(在“/”上),创建哈希树,然后使用Data::TreeDumper打印该树。 Kinda hacky,但它的工作原理是:

#!/usr/bin/perl
use strict;
use warnings;

use Data::TreeDumper;

my %tree;
while (<>) {
my $t = \%tree;
foreach my $part (split m!/!, $_) {
next if $part eq '';
chomp $part;
$t->{$part} ||= {};
$t = $t->{$part};
}
}
sub check_tree {
my $t = shift;
foreach my $hash (values %$t) {
undef $hash unless keys %$hash;
check_tree($hash);
}
}
check_tree(\%tree);
my $output = DumpTree(\%tree);
$output =~ s/ = undef.*//g;
$output =~ s/ \[H\d+\].*//g;
print $output;

这是输出:

$ perl test.pl test.data

|-水果
| |-苹果
| | |-绿色
| | |-红色
| | `-黄色
| |-香蕉
| | |-绿色
| | `-黄色
| `-橙色
| |-绿色
| `-橙色
|-i_want_my_mommy
`-人
|-男人
| |-鲍勃
| `-大卫
`-女人
前夕

关于unix - 将类似 `find`的输出转换为类似 `tree`的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4420878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com