簡體   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