2

I can't use the "dirname" command because this is a string and not a really directory. So, I extract my dirname and filename only using regexp.

Example:

filefolder=/home/ubuntu/Desktop/photo.jpg

If I want to extract the filename, I use: filename=${filefolder##*/}. It works, and returns as result: "photo.jpg".

If I want to extract the dirname, what kind of regexp can I use? I've tried with NOT operator before "*/" in this way: dirname=${filefolder##^[*/]} but doesn't work.

Any idea to solve it?

1 Answers1

2

The opposite of the ${..##..} is ${..%%..}:

~$ filefolder=/home/ubuntu/Desktop/photo.jpg
~$ filedir=${filefolder%/*}
~$ echo $filedir
/home/ubuntu/Desktop

It's one of the parameter substitution:

${var%Pattern}, ${var%%Pattern}

${var%Pattern} Remove from $var the shortest part of $Pattern that matches the back end of $var.

${var%%Pattern} Remove from $var the longest part of $Pattern that matches the back end of $var.

An alternative is to use the dirname/basename commands:

~$ dirname $filefolder
/home/ubuntu/Desktop
~$ basename $filefolder
photo.jpg
Community
  • 1
  • 1
fredtantini
  • 15,966
  • 8
  • 49
  • 55