David Y.
—Given a file path string in Bash, how can I reliably extract the filename and extension, even in cases where the name contains multiple .
s? For example, I would like to extract the name “requirements.updated” and extension “txt” in separate variables from this string:
/home/user/requirements.updated.txt
We can achieve this in Bash using the basename
command and parameter expansion.
First, extract the filename from the path using basename
:
filepath="/home/user/requirements.updated.txt" filename_with_ext=$(basename "$filepath")
Next, use parameter expansion to separate the filename and extension:
filename="${filename_with_ext%.*}" extension="${filename_with_ext##*.}"
In the first line, the ${filename_with_ext%.*}
parameter expansion will remove the shortest match of .*
from the end of $filename_with_ext
, removing only the final .
and text after it.
In the second line, the ${filename##*.}
parameter expansion will remove the longest match of *.
from the beginning of $filename_with_ext
, leaving us with just the text after the final .
.
Our full Bash script will look like this:
#!/bin/bash filepath="/home/user/requirements.updated.txt" filename_with_ext=$(basename "$filepath") filename="${filename_with_ext%.*}" extension="${filename_with_ext##*.}" echo "Path: $filepath" echo "Filename with extension: $filename_with_ext" echo "Filename without extension: $filename" echo "File extension: $extension"
When run, this script will produce the output below:
Path: /home/user/requirements.updated.txt Filename with extension: requirements.updated.txt Filename without extension: requirements.updated File extension: txt
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.