Bash is a powerful command-line shell that is commonly used in Linux and Unix operating systems. One common task when working with files in Bash is to extract the filename and extension from a file path. This article will discuss how to extract the filename and extension in Bash and provide examples of how to use these values in your scripts.
Extracting the Filename and Extension in Bash
There are several ways to extract the filename and extension in Bash, here are three common methods:
1: Using the Basename Command
The basename command returns the filename from a file path and extracts the filename and extension. You can use the basename command with the –suffix option, which removes the specified suffix from the filename as in the below-given code:
# Example file path
file_path="/path/to/file.txt"
Â
# Extract filename
filename=$(basename $file_path)
Â
# Extract extension
extension="${filename##*.}"
Â
echo "Filename: $filename"
echo "Extension: $extension"
2: Using the Parameter Expansion
The parameter expansion syntax is a powerful feature of Bash that allows you to manipulate strings. To extract the filename and extension using parameter expansion, you can use the ${parameter##word} syntax, which removes the longest match of the specified pattern from the beginning of the parameter as in the code below:
# Example file path
file_path="/path/to/file.txt"
# Extract filename
filename="${file_path##*/}"
# Extract extension
extension="${filename##*.}"
echo "Filename: $filename"
echo "Extension: $extension"
3: Using the IFS (Internal Field Separator) Variable
The IFS variable is used by Bash to split strings into fields by setting the IFS variable to the path separator (“/”). You can extract the filename and extension from a file path through this variable using the below-given code:
# Example file path
file_path="/path/to/file.txt"
# Set IFS to "/"
IFS="/" read -r -a parts <<< "$file_path"
Â
# Extract filename
filename="${parts[-1]}"
# Extract extension
extension="${filename##*.}"
echo "Filename: $filename"
echo "Extension: $extension"
Conclusion
Extracting the filename and extension from a file path is a common task when working with files in Bash. This article discussed three common methods for extracting the filename and extension in Bash. By using the basename command, the parameter expansion syntax, or the IFS variable, you can quickly and easily extract the filename and extension values from a file path.