Ubuntu: sed the string and hold the value in new variable


I have this String cap/media/101/101.mp4 and I need to cut the 101 in another Variable.

I am trying to do it with sed but it's not giving me the output I need.

echo cap/media/101/101.mp4 | sed -e 's/d/\(.*\)/\1/'  

can someone please give an idea about it?


Assuming you want the characters between media/ and the next / (based on what you said in the comments) you could cut that part with

sed -r 's|.*media/([^/]+).*|\1|'  


  • -r use ERE (so we don't have to escape () or + to use them as metacharacters
  • s|old|new| replace old with new (using an alternative delimiter to avoid having to escape / in the string)
  • ([^/]+) save some characters that are not /
  • \1 the saved pattern (the rest is discarded)


Assuming consistent fields, a simple awk command can do the trick:

echo cap/media/101/101.mp4 | awk -F"/" '{print $3}'  




(Late to the party :)). So many ways to skin this cat...Here are a few:

Here, i am getting the digits surrounded by /:

With cut:

cut -d/ -f3   

With grep:

grep -Po '/\K\d+(?=/)'  

With perl:

perl -F/ -lane 'print $F[2]'  

With python:

python3 -c 'import sys; i=sys.stdin.read().split("/"); print(i[2])'  

Another sed:

sed -E 's#.*/([0-9]+)/.*#\1#'   

Another awk (though the already provided awk answer getting the / delimited 3rd field should be the way to go):

awk '{i=gensub(".*/([0-9]+)/.*", "\\1", "g"); print i}'  

With go:

package main    import (      "fmt"      "strings"  )    func main() {      str := "cap/media/101/101.mp4"      fmt.Println(strings.Split(str, "/")[2])  }  


% cut -d/ -f3 <<<'cap/media/101/101.mp4'                                                            101    % grep -Po '/\K\d+(?=/)' <<<'cap/media/101/101.mp4'  101    % perl -F/ -lane 'print $F[2]' <<<'cap/media/101/101.mp4'                                           101    % python3 -c 'import sys; i=sys.stdin.read().split("/"); print(i[2])' <<<'cap/media/101/101.mp4'  101    % sed -E 's#.*/([0-9]+)/.*#\1#' <<<'cap/media/101/101.mp4'  101    % awk '{i=gensub(".*/([0-9]+)/.*", "\\1", "g"); print i}' <<<'cap/media/101/101.mp4'  101    ## Go Playground: https://play.golang.org/p/kGdzyywEB2  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »