Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash extracting file basename from long path

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 !

like image 704
Benoit B. Avatar asked Sep 17 '13 09:09

Benoit B.


People also ask

How do you segregate a basename and extension of a file in Linux?

Sometimes the users need to read the basename of the file only by removing the file extension. Filename and extension can be separated and stored on different variables in Linux by multiple ways. Bash built-in command and shell parameter expansion can be used to remove the extension of the file.

What is basename in bash?

In Linux, the basename command prints the last element of a file path. This is especially useful in bash scripts where the file name needs to be extracted from a long file line. The “basename” takes a filename and prints the filename's last portion. It can also delete any following suffix if needed.

How do I find a file path in bash?

In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.


1 Answers

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
like image 64
dogbane Avatar answered Sep 21 '22 08:09

dogbane