繁体   English   中英

如何在匹配前后对模式进行 sed

[英]how to sed for pattern before and after match

我目前正在尝试从 url 获取特定参数。

我的网址看起来像: https://private.io/report-artifact/dsop-pipeline-artifacts/container-scan-reports/redhat/ubi/ubi7/7.8/2020-02-14T222203.548_2868/ubi7-7.8.tar : https://private.io/report-artifact/dsop-pipeline-artifacts/container-scan-reports/redhat/ubi/ubi7/7.8/2020-02-14T222203.548_2868/ubi7-7.8.tar

我只想要redhat/ubi/ubi7/7.8

我可以通过这样redhat/ubi/ubi7/7.8/2020-02-14T222203.548_2868/ubi7-7.8.tar

echo https://private.io/report-artifact/dsop-pipeline-artifacts/container-scan-reports/redhat/ubi/ubi7/7.8/2020-02-14T222203.548_2868/ubi7-7.8.tar | sed 's|.*/container-scan-reports/||'

因此我想删除/2020-02-14T222203.548_2868/ubi7-7.8.tar

我还想将/更改为-以便我拥有redhat-ubi-ubi7-7.8

使用 GNU sed

.*/container-scan-reports/之后获取以下 4 个路径元素,并将所有/替换为-

url='https://private.io/report-artifact/dsop-pipeline-artifacts/container-scan-reports/redhat/ubi/ubi7/7.8/2020-02-14T222203.548_2868/ubi7-7.8.tar'
echo "$url" | sed -E 's|.*/container-scan-reports/(([^/]*/){3}[^/]*).*|\1|;s|/|-|g'

或者你可以获得.*/container-scan-reports/ ,但不是最后两个路径元素:

echo "$url" | sed -E 's|.*/container-scan-reports/(.*)/[^/]*/[^/]*|\1|;s|/|-|g'

当您知道字符串中的位置时,您可以使用cut

echo "${string}" | cut -d/ -f 7-10 | tr '/' '-'

sed另一种方法是

echo "${string}" | sed -E 's#([^/]*/){6}([^/]*)/([^/]*)/([^/]*)/([^/]*).*#\2-\3-\4-\5#'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM