How to get the last part of '/' separated string in shell script
本问题已经有最佳答案,请猛点这里访问。
我有一个字符串如下
1 | "hub.docker.corp.net/suite/content-install:latest" |
我需要从中获取"内容安装"..
所以,如果任何这样的字符串我需要提取最后一部分的左侧部分
所以,如果字符串是
1 | "aaaa/bbbb/cccc/dddd/eee:ff" |
那我只需要"eee"
提前致谢
1 2 3 4 | echo $x aaaa/bbbb/cccc/dddd/eee:ff echo $x |sed -r 's|(^.*)/(.*?):(.*)|\2|' eee |
这是使用
或者使用
1 2 | echo $x |grep -oP '^.*/\K.*?(?=:)' eee |
这是从线的起点到最后
我会使用一点修改@ PS。的解决方案:
1 | grep -oP '^(.*/)?\K.*?(?=:|\z)' |
测试一些不同的输入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | (echo"INPUT=RESULT" while read -r from do base=$(grep -oP '^(.*/)?\K.*?(?=:|\z)' <<<"$from") echo"$from=${base:-UNDEFINED}" done <<'EOF') | column -s= -t /aaa/bb:bb/fff:xx /fff:xx /fff: /fff /:xx / ./aaa/bb:bb/fff:xx ./fff:xx ./fff: ./fff ./:xx ./ aaa/bb:bb/fff:xx fff:xx fff: fff :xx EOF |
版画
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | INPUT RESULT /aaa/bb:bb/fff:xx fff /fff:xx fff /fff: fff /fff fff /:xx UNDEFINED / UNDEFINED ./aaa/bb:bb/fff:xx fff ./fff:xx fff ./fff: fff ./fff fff ./:xx UNDEFINED ./ UNDEFINED aaa/bb:bb/fff:xx fff fff:xx fff fff: fff fff fff :xx UNDEFINED |
@Beatrix:试试:
1 2 3 4 | echo"aaaa/bbbb/cccc/dddd/eee:ff" | awk -F'[/:]' '{print $(NF-1)}' awk -F'[/:]' ##### making field separator as / and :, so in awk by default delimiter is space so I am making it according to your requirements. '{print $(NF-1)}' ##### now printing the $(NF-1) field which is second last field of the line. |
您也可以使用
1 | basename"hub.docker.corp.net/suite/content-install:latest" | cut -d':' -f1 |
1 | echo"hub.docker.corp.net/suite/content-install:latest"|sed -r 's#.*/([^:]+).*#\1#' |