对我之前的问题的扩展。下面的sed输出已经与特定的文件模式相匹配:[Ll]earning
grep [Ll]earning <file>
<match output is...>
/Volumes/WD/A/machinelearning-2018-12-01-07_26_05.pdf
/Volumes/WD/A/SomeLearningIsGood/Path/machinelearning-2018-12-01-07_26_05.pdf我希望在每个匹配级别(sed/awk)上转换上面的输出,以包含并附加一个转换。转换标识到与模式(如果有的话)匹配的最左边目录的路径。分隔符可以类似于":“。如果模式[Ll]earning没有最左边匹配的目录,则打印0,否则打印到最左边的目录。在上面的第二个匹配中,“/量/WD/A/SomeLearningIsGood/”是路径结构中最左边的匹配目录,因此它被附加到其各自的文件模式匹配中。
<expected output>
/Volumes/WD/A/machinelearning-2018-12-01-07_26_05.pdf : 0
/Volumes/WD/A/SomeLearningIsGood/Path/machinelearning-2018-12-01-07_26_05.pdf : /Volumes/WD/A/SomeLearningIsGood/我知道,显示最左边匹配的dir的实际表达式是:
sed -n 's/\([Ll]earning[^/]*\/\).*/\1/p' file
matches:
/Volumes/WD/A/SomeLearningIsGood/Update试图在bash 3脚本中的Mac (BSD /awk)上执行此操作。在BSD上运行的问题。见更新2。
Update 2通过MacPorts/安装gsed (Gsed),并遵循@的解决方案。就像一种魅力。
brew install gnu-sed
port install gsed发布于 2019-12-05 18:39:16
这可能就是你要找的:
sed -En '\@[Ll]earning[^/]*/@{h;s@([Ll]earning[^/]*/).*@\1@;H;x;s/\n/ : /p;t};s/.*[Ll]earning.*/& : 0/p'不需要预先设置一个grep,它在没有学习的情况下过滤掉结果。
你可以在这里试试。
下面是一个符合POSIX标准的备选方案:
sed -n '/[Ll]earning[^\/]*\//{h;s/\([Ll]earning[^\/]*\/\).*/\1/;H;x;s/\n/ : /p;t};s/.*[Ll]earning.*/& : 0/p'你可以在这里试试。
另外,如果您不需要在没有波顿氏液的情况下过滤出行,请检查[Ll]earning,这要简单得多!
https://stackoverflow.com/questions/59200187
复制相似问题