awk - 使用 sed/awk 在目录之间添加栏

标签 awk sed

我正在使用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

我想将其通过管道传输到 sedawk 中进行轻微更改:在任何目录列表的末尾,插入换行符 + 文字 |:

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/

相关文章:

ubuntu - awk 查找字符串完全匹配的行号

linux - 使用sed删除文件中的行

linux - 结合greps制作脚本来计算文件夹中的文件

linux - 如何根据Linux中的条件(使用awk或其他方法)从另一个csv文件中的一个csv文件中替换行?

regex - 使用sed替换仅用引号引起来的文本

sed:删除日志文件中的重复模式

Unix:cut 或 awk 命令中的多字符和单字符分隔符

bash - 将字符串添加到文件开头,将另一个字符串添加到文件末尾

macos - 如何使用 sed 替换源文件中的版权/许可证 header ?

shell - sed命令替换空格和:之间的数字