简体   繁体   中英

how to sed for pattern before and after match

I currently am trying to get specific parameters from a url.

My url looks like: 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

I want just redhat/ubi/ubi7/7.8

I can get redhat/ubi/ubi7/7.8/2020-02-14T222203.548_2868/ubi7-7.8.tar by doing,

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/||'

Thus I want to remove /2020-02-14T222203.548_2868/ubi7-7.8.tar

I also would like to change the / to a - so that I have redhat-ubi-ubi7-7.8

With GNU sed :

Get the 4 following path elements after .*/container-scan-reports/ and replace all / with - :

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'

Or you could get everything after .*/container-scan-reports/ , but not the last two path elements:

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

When you know the position in the string you can use cut

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

Another way with sed is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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