我正在使用tree
递归显示目录的实用程序如下:
$ tree -F -a --dirsfirst project
project
├── my_app/
│ └── __init__.py
└── tests/
├── integration/
│ ├── __init__.py
│ └── test_integration.py
└── unit/
├── __init__.py
└── test_sum.py
$ tree -F -a --dirsfirst helloworld
helloworld
├── helloworld/
│ ├── __init__.py
│ ├── helloworld.py
│ └── helpers.py
├── tests/
│ ├── helloworld_tests.py
│ └── helpers_tests.py
├── .gitignore
├── LICENSE
├── README.md
├── requirements.txt
└── setup.py
我想将其通过管道传输到 sed
或 awk
中进行轻微更改:在任何目录列表的末尾,插入换行符 + 文字 |
:
project/
├── my_app/
│ └── __init__.py
│
└── tests/
├── integration/
| ├── __init__.py
| └── test_integration.py
|
└── unit/
├── __init__.py
└── test_sum.py
helloworld/
├── helloworld/
│ ├── __init__.py
│ ├── helloworld.py
│ └── helpers.py
│
├── tests/
│ ├── helloworld_tests.py
│ └── helpers_tests.py
│
├── .gitignore
├── LICENSE
├── README.md
├── requirements.txt
└── setup.py
如何进行此替换?
当前尝试和逻辑:换行符 + |
插入到前导 │
之后和前导 ├──
之前(两者之前可选空格)其中):
tree -F -a --dirsfirst helloworld | sed -E 's/^\s*\│.*\n\s*\├──/???/g'
卡在了那里——对 Python 的 re
和一些 grep
的熟练程度比 sed/awk 强 100 倍。
最佳答案
这是使用 Perl 的可能解决方案:
perl -pe 'if (/│.*└/) { print; s/ *└.*// }'
想法:
对于后面某处包含 │
和 └
的每一行,修剪 └
以及所有后续字符和所有前面的空格,然后输出修改后的行。
效果:
│ │ └── foo.xyz
后跟一个新行,其中仅包含
│ │
在输出中。
Sed 版本:
sed '/│.*└/{p;s/ *└.*//}'
对于您的示例输入,它会生成以下输出:
$ tree -F -a --dirsfirst project
project
├── my_app/
│ └── __init__.py
│
└── tests/
├── integration/
│ ├── __init__.py
│ └── test_integration.py
│
└── unit/
├── __init__.py
└── test_sum.py
$ tree -F -a --dirsfirst helloworld
helloworld
├── helloworld/
│ ├── __init__.py
│ ├── helloworld.py
│ └── helpers.py
│
├── tests/
│ ├── helloworld_tests.py
│ └── helpers_tests.py
│
├── .gitignore
├── LICENSE
├── README.md
├── requirements.txt
└── setup.py
关于awk - 使用 sed/awk 在目录之间添加栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54954472/