2

How get the file in these strings?

/home/streaming/demo/youtube/Surf9B.mp4
/home/streaming/demo/Surf9B.mp4
/home/streaming/demo/youtube/test/Surf9B.mp4

I need to get only the Surf9B.mp4 and store in a new variable.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Insert
  • 17
  • 2

2 Answers2

1
$ basename /home/streaming/demo/youtube/Surf9B.mp4
Surf9B.mp4

$ file=`basename /home/streaming/demo/youtube/Surf9B.mp4`
$ echo "$file"
Surf9B.mp4
Rob Davis
  • 15,597
  • 5
  • 45
  • 49
  • 1
    Consider using lower-case variable names in examples. POSIX specifies all-uppercase names for use for variables meaningful to shell and system utilities, and specifies the namespace with at least one lowercase character as reserved for application use. See fourth paragraph of http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html (on environment variables, but namespace conventions apply to shell variables as well since setting a shell variable with a name that overlaps an environment variable defined at the time will overwrite the latter). – Charles Duffy Nov 11 '16 at 23:03
  • Also consider quoting your expansions. `echo "$file"` is safer than `echo $file`: Without quotes in use, if the filename contains any characters in IFS they'll be replaced with spaces; if the filename can be interpreted as a glob, it'll be replaced with expansion results if they exist (and behavior if no results exist are heavily dependent on shell option configuration: `failglob` and `nullglob` both apply). – Charles Duffy Nov 11 '16 at 23:08
0

You could try something like this, but you names cannot include a "/" in them.

SOME_VAR=$(echo "/home/streaming/demo/youtube/Surf9B.mp4" | rev | cut -f1 -d'/' | rev)
echo $SOME_VAR
  • You're running... let's see, `$()` forks one subprocess, then `rev`, `cut`, and the second `rev` are also additional external tools... so a total of *four* new programs, just to do something bash can do built-in?! – Charles Duffy Nov 11 '16 at 23:02
  • 1
    `filename=/home/streaming/demo/youtube/Surf9B.mp4; echo "${filename##*/}"` – Charles Duffy Nov 11 '16 at 23:02
  • ...moreover, `rev` is not part of POSIX, part of bash, or even part of the Linux Standards Base, so there's no guarantee it'll be installed on any given system. – Charles Duffy Nov 11 '16 at 23:05