-4

I have a string as below

"hub.docker.corp.net/suite/content-install:latest"

I need to get the "content-install" from it..

So if any such string i need to extract the left portion of the last part

So if the string is

"aaaa/bbbb/cccc/dddd/eee:ff"

then i need only "eee"

Thanks in advance

Zumo de Vidrio
  • 2,021
  • 2
  • 15
  • 33
Beatrix Kiddo
  • 199
  • 1
  • 2
  • 10
  • 1
    Did you make an attempt? – Inian Mar 10 '17 at 08:16
  • Please [edit] your question to show [what you have tried so far](http://whathaveyoutried.com). You should include at least an outline (but preferably a [mcve]) of the code that you are having problems with, then we can try to help with the specific problem. You should also read [ask]. – Toby Speight Mar 10 '17 at 12:58

5 Answers5

3
echo $x
aaaa/bbbb/cccc/dddd/eee:ff
echo $x |sed -r 's|(^.*)/(.*?):(.*)|\2|'
eee

This is using sed with back referencing. Here, line is divided into chunks and the desired chunk of the line is referred in the replace field using \2 for the second field.

Or using grep :

echo $x |grep -oP '^.*/\K.*?(?=:)'
eee

This is discarding everthing from the start of the line till last /. then it will print the text which is preceding :.

P....
  • 17,421
  • 2
  • 32
  • 52
2

@Beatrix: try:

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.
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
2

I would use a bit modified @PS.'s solution:

grep -oP '^(.*/)?\K.*?(?=:|\z)'

Test for some different inputs:

(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

prints

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
clt60
  • 62,119
  • 17
  • 107
  • 194
1

You can also do it with basename and cut:

basename "hub.docker.corp.net/suite/content-install:latest" | cut -d':' -f1

basename will provide the whole string after the last "/" and with that cut command you get the string before the ":" delimiter.

Zumo de Vidrio
  • 2,021
  • 2
  • 15
  • 33
0
echo "hub.docker.corp.net/suite/content-install:latest"|sed -r 's#.*/([^:]+).*#\1#'
mop
  • 423
  • 2
  • 11