Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get just the filename from a path in a Bash script [duplicate]

How would I get just the filename without the extension and no path?

The following gives me no extension, but I still have the path attached:

source_file_filename_no_ext=${source_file%.*} 
like image 548
Keith Avatar asked Jul 29 '10 13:07

Keith


People also ask

How do I find the path of a file 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.

How do I get filenames without an extension in Unix?

If you want to retrieve the filename without extension, then you have to provide the file extension as SUFFIX with `basename` command. Here, the extension is “. txt”.

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.


1 Answers

Many UNIX-like operating systems have a basename executable for a very similar purpose (and dirname for the path):

pax> full_name=/tmp/file.txt pax> base_name=$(basename ${full_name}) pax> echo ${base_name} file.txt 

That unfortunately just gives you the file name, including the extension, so you'd need to find a way to strip that off as well.

So, given you have to do that anyway, you may as well find a method that can strip off the path and the extension.

One way to do that (and this is a bash-only solution, needing no other executables):

pax> full_name=/tmp/xx/file.tar.gz pax> xpath=${full_name%/*}  pax> xbase=${full_name##*/} pax> xfext=${xbase##*.} pax> xpref=${xbase%.*} pax> echo "path='${xpath}', pref='${xpref}', ext='${xfext}'"  path='/tmp/xx', pref='file.tar', ext='gz' 

That little snippet sets xpath (the file path), xpref (the file prefix, what you were specifically asking for) and xfext (the file extension).

like image 142
paxdiablo Avatar answered Sep 17 '22 19:09

paxdiablo