How to Extract filename and extension in Bash?
Understand Extract filename and extension in Bash
Syntax
In Bash, you can extract the filename and extension from a file path using the following syntax:
filename="${path##*/}"
extension="${filename##*.}"
filename_no_ext="${filename%.*}"
Let's break down the syntax:
path
is the variable that holds the file path."${path##*/}"
extracts the filename from the path by removing everything up to and including the last forward slash."${filename##*.}"
extracts the extension from the filename by removing everything up to and including the last dot."${filename%.*}"
extracts the filename without extension by removing the shortest possible match of anything after the last dot.
Example
Here's an example that shows this in use:
path="/usr/local/bin/example.sh"
filename="${path##*/}"
extension="${filename##*.}"
filename_no_ext="${filename%.*}"
echo "Filename: $filename"
echo "Extension: $extension"
echo "Filename without extension: $filename_no_ext"
This will output:
Filename: example.sh
Extension: sh
Filename without extension: example
Related Bash Tutorials
- Dynamic variable names in Bash
- How to parse command line arguments in Bash?
- Bash and shell script variable capitalization?
- How to get the directory where a Bash script is located from within the script itself?
- Parsing JSON with Unix tools
- Command not found error in Bash variable assignment
- How to set a variable to the output of a command in Bash?
- How to run Bash commands in Python? 9.Looping through the content of a file in Bash
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go