- Get just the filename from a path in a Bash script [duplicate]
- 6 Answers 6
- How to Get Filename From Path in Bash?
- Method 1: How to Get File Name From the Path Using Bash script?
- Method 2: How to Get File Name From the Path Using Basename Command?
- Syntax:
- Bonus Tip: How to Get and Remove Extensions From the File Name?
- Conclusion
- Extract Filename and Extension in Bash
- Method 1: Using the basename Command
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=$
6 Answers 6
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 $) pax> echo $ 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=$ pax> xbase=$ pax> xfext=$ pax> xpref=$ pax> echo "path='$', pref='$', ext='$'" 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).
I know there is something to do with bash like the above. I just don’t know what the key word is. I would like to get get the pathname, filename, and extension separated into different variables.
If you want to get path use: path=$(echo $filename | sed -e ‘s/\/[^\/]*$/\//’) If you want to get extension: ext=$(echo $filename | sed -e ‘s/[^\.]*\.//’)
@Keith: for pathname, use path=$(dirname $filename) ; there isn’t a command to give you the extension per se, but @paxdiablo showed you how the shell can do it.
@Startec, because that’s how you run an executable (like basname ), capture it’s output, and use that output within a bash command as if you had typed it in explicitly. It’s similar to using backticks but with greater ease of nesting where necessary.
basename and dirname solutions are more convenient. Those are alternative commands:
FILE_PATH="/opt/datastores/sda2/test.old.img" echo "$FILE_PATH" | sed "s/.*\///"
This returns test.old.img like basename .
This is salt filename without extension:
And following statement gives the full path like dirname command.
It returns /opt/datastores/sda2
this doesn’t work if your path is just file.txt . your second code snipper should be sed -r «s/(.+\/)?(.+)\..+/\2/ instead
I’ve tested @Cardin. seems it works. FILE_PATH=»file.txt»; echo «$FILE_PATH» | sed «s/.*\///»; echo «$FILE_PATH» | sed -r «s/.+\/(.+)\..+/\1/»; echo «$FILE_PATH» | sed -r «s/(.+)\/.+/\1/»; returns 3 times file.txt
Here is an easy way to get the file name from a path:
echo "$PATH" | rev | cut -d"/" -f1 | rev
To remove the extension you can use, assuming the file name has only ONE dot (the extension dot):
That’s not a good assumption, and there are tools and commands specificly designed to do this properly.
Additionally, I wouldn’t recommend using the variable name PATH , since this can conflict with the system’s PATH variable
This returns «bad substitution» in bash v4.4.7. I think Fırat KÜÇÜK’s sed solution is better, i.e. $(basename $the_file_path) | sed «s/\..*//»
For me this also gives «bad substitution» error in Bash 4.2.46. But it works if I replace order of operators, i.e. file=$(basename $
Some more alternative options because regexes (regi ?) are awesome!
Here is a Simple regex to do the job:
Example (grep):
FP="/hello/world/my/file/path/hello_my_filename.log" echo $FP | grep -oP "$regex" #Or using standard input grep -oP "$regex"
Example (awk):
echo $FP | awk 'END #Or using stardard input awk 'END
If you need a more complicated regex: For example your path is wrapped in a string.
StrFP="my string is awesome file: /hello/world/my/file/path/hello_my_filename.log sweet path bro." #this regex matches a string not containing / and ends with a period #then at least one word character #so its useful if you have an extension regex="[^/]*\.\w" #usage grep -oP "$regex"
Total solution with Regexes:
This function can give you the filename with or without extension of a linux filepath even if the filename has multiple "."s in it. It can also handle spaces in the filepath and if the file path is embedded or wrapped in a string.
#you may notice that the sed replace has gotten really crazy looking #I just added all of the allowed characters in a linux file path function Get-FileName()< local FileString="$1" local NoExtension="$2" local FileString=$(echo $FileString | sed 's:\(/[a-zA-Z0-9\\|\\\:\)\(\&\;\,\?\*]*\)\( \)\([a-zA-Z0-9\\|\\\:\)\(\&\;\,\?\*]*/\):\1\3:g') local regex="(? ## call the function with extension Get-FileName "my string is awesome file: /hel lo/world/my/file test/path/hello_my_filename.log sweet path bro." ##call function without extension Get-FileName "my string is awesome file: /hel lo/world/my/file test/path/hello_my_filename.log sweet path bro." "1"
If you have to mess with a windows path you can start with this one:
How to Get Filename From Path in Bash?
In Linux, bash script is a shell in which commands are written in sequence. Users can write anything in the bash script, such as programs and commands, and run it to get the file’s output. Using this user can also get file names from the path. In this post, you will learn to get file names from the path using the bash script. The post’s content is as follows:
Method 1: How to Get File Name From the Path Using Bash script?
The file name can easily be obtained using the Bash script. Create a bash script file and type the script into the file, make the file executable, and run that file to get the output. Let’s implement and learn this method in the following steps.
Step 1: Create the Bash Script File
Create the file with the .sh extension using the touch command. To create the file is obtained as follows:
The file will be created, as can be seen in the above image.
Step 2: Make the File Executable
Make executable using the “chmod” command. To do so, the following command will be used:
To verify that file is executable, run the following command in the terminal:
The above image shows the executable permission for the user.
Step 3: Type the Script
Now, you need to type the script inside a bash shell of the file by typing the below command and pressing enter:
After entering, type the below script and save the file:
#!/bin/bash filepath="/home/linuxfoss.txt.gz" filename=$ echo $filename
You can also open the file manually for typing the script:
Let’s move to the next step.
Step 4: Run the Bash Script File
Run the Bash file in the terminal to check the output. To do so, the following command is useful:
The above image has displayed the file name.
Note: File name can also be used by the terminal through bash script parameters. To do so, execute the following command one by one:
$ filepath="/home/linuxfoss.txt.gz" $ filename=$ $ echo $filename
Let’s move to the second method to get the file name.
Method 2: How to Get File Name From the Path Using Basename Command?
The Basename command is used to print the base path (excluding the parent path), which is useful in the bash script of the file where the user can extract the file name. The syntax for the basename command is given below:
Syntax:
Let’s check the base command in the bash script:
Open your bash file with nano editor. To do so, execute this command in the terminal:
Once you enter the above command, this will take you to the editor. Now, add the command in the script:
#!/bin/bash Basename /home/linuxfoss.txt.gz
Save the file by pressing “Ctrl+O” and exit from the editor using “Ctrl+X”.
Run the bash script to check the file output:
The output shows that the file name has been retrieved from the path.
For multiple paths, the following command will be used; we are using three paths to get file names:
#!/bin/bash basename -a /home/foss.txt /home/linuxfoss.txt.gz /home/get-pip.py
Put this command in the bash script file:
Save and run the file to check the output:
All three file names have been displayed, as shown in the above image.
Bonus Tip: How to Get and Remove Extensions From the File Name?
You can also get the extension from the bash script from the filename. For this feature, type the following script into the bash file:
#!/bin/bash filepath="/home/linuxfoss.txt.gz" echo "$"
After that, run the bash file using the following command:
The above command will display only the extension of the file name, which can be seen in the above image.
Conclusion
In Linux, file names can be obtained using the bash file through a bash script, bash script parameters, or the basename command. In this article, all the possible ways to get file names from the path have been demonstrated. Apart from that, methods to get an extension from the file name or remove the extension from the file name have also been illustrated in this post.
Extract Filename and Extension in Bash
There are many reasons why you might want to extract the filename and extension of a file in Bash:
- To manipulate the file name or extension - You may want to extract the filename or extension in order to modify it, such as adding a prefix or suffix to the file name, or changing the file extension.
- To create a file with a unique name - You may want to extract the filename and extension in order to create a new file with a unique name, such as by adding a timestamp or a random number to the file name.
- To use the filename or extension in a script or command - You may want to extract the filename or extension in order to use it as an argument or input for a script or command, such as to pass it to a program or to create a file with the same name as a directory.
- To extract information from the file name or extension - You may want to extract the filename or extension in order to extract information from it, such as the date or the file type.
In this article, we'll take a look at the three most common ways you can extract filename and file extension in Bash. We'll take a look at each of them and give you the pros and cons, so you can make an educated decision on what approach suits you the best.
Method 1: Using the basename Command
The basename command can be used to extract the filename and extension from a file path:
filename=$(basename /path/to/file.txt) echo $filename # Output: "file.txt"
Although this method is quite simple and easy to use, unfortunately, there is no way we can extract only the file name (with no extension) without any post-processing.
You can also use the dirname command to extract the directory path separately:
directory=$(dirname /path/to/file.txt) echo $directory # Output: "/path/to"