Skip to content

Get file name from path

Using the basename command

One of the easiest ways to get the file name from a path is to use the basename command. The basename command takes a path as an argument and returns only the file name without the path. Here is an example:

path="/home/user/documents/file.txt"
filename=$(basename "$path")
echo "$filename"

This will output file.txt, which is the file name extracted from the path.

Using parameter expansion

Another way to extract the file name from a path is to use parameter expansion. This is a Bash feature that allows you to manipulate variables. In this case, we can manipulate the path variable to extract only the file name. Here is an example:

path="/home/user/documents/file.txt"
filename="${path##*/}"
echo "$filename"

This will also output file.txt.

Using regular expressions

If you need more control over the file name extraction process, you can use regular expressions. Regular expressions are a powerful tool for pattern matching and can be used to extract specific parts of a string. Here is an example:

path="/home/user/documents/file.txt"
if [[ "$path" =~ /([^/]+)$ ]]; then
  filename=${BASH_REMATCH[1]}
  echo "$filename"
fi

This will output file.txt as well.

Conclusion

Extracting file names from paths is a common task when working with Bash scripts. In this blog post, we explored three different methods for achieving this: using the basename command, parameter expansion, and regular expressions. Each method has its own advantages and disadvantages, so choose the one that works best for your specific use case.

Feedback