To extract the filename and extension from a file path in Bash on a Unix or Linux system, you can use parameter expansion and the basename
command.
Here is an example of using parameter expansion to extract the filename and extension from a file path:
path="/path/to/file.txt" filename=${path##*/} # Extract the filename with extension extension=${filename##*.} # Extract the extension echo "Filename: $filename" echo "Extension: $extension"
This will extract the filename and extension from the path
variable, and print them to the terminal.
The ##*/
operator removes the longest match for */
from the beginning of the path
variable, which leaves the filename with extension. The ##*.
operator removes the longest match for *.
from the beginning of the filename
variable, which leaves the extension.
Alternatively, you can use the basename
command to extract the filename and extension from a file path.
Here is an example of using the basename
command to extract the filename and extension:
path="/path/to/file.txt" filename=$(basename "$path") # Extract the filename with extension extension="${filename##*.}" # Extract the extension echo "Filename: $filename" echo "Extension: $extension"
This will extract the filename and extension from the path
variable in the same way as the previous example.
Keep in mind that the basename
command may not be available on all Unix and Linux systems. In that case, you can use the parameter expansion method to extract the filename and extension from a file path.