Bash extracting file basename from long path

Benoit B. picture Benoit B. · Sep 17, 2013 · Viewed 34.7k times · Source

In bash I am trying to glob a list of files from a directory to give as input to a program. However I would also like to give this program the list of filenames

files="/very/long/path/to/various/files/*.file"

So I could use it like that.

prompt> program -files $files -names $namelist

If the glob gives me :

/very/long/path/to/various/files/AA.file /very/long/path/to/various/files/BB.file /very/long/path/to/various/files/CC.file /very/long/path/to/various/files/DD.file /very/long/path/to/various/files/ZZ.file

I'd like to get the list of AA BB CC DD ZZ to feed my program without the long pathname and file extension. However I have no clue on how start there ! Any hint much appreciated !

Answer

dogbane picture dogbane · Sep 17, 2013

It's better to use an array to hold the filenames. A string variable will not handle filenames which contain spaces.

Also, you don't need to use the basename command. Instead use bash's built-in string manipulation.

Try this:

files=( /very/long/path/to/various/files/*.file )
for file in "${files[@]}"
do
  filename="${file##*/}"
  filenameWithoutExtension="${filename%.*}"
  echo "$filenameWithoutExtension"
done