ARTICLE - Developer Tools

Regex-Style Path Extraction Tricks in Linux Shell

When you write shell scripts, one of the most common tasks is extracting parts of a path: the filename, the directory, the extension, or a parent folder.

2023-04-03 cnblogs.com (CQZHUOMI)

Regex-Style Path Extraction Tricks in Linux Shell

When you write shell scripts, one of the most common tasks is extracting parts of a path: the filename, the directory, the extension, or a parent folder. It looks small, but a single mistake can cause a deployment script to target the wrong folder or write files to the wrong location.

Assume a file path:

file=/dir1/dir2/dir3/my.file.txt

We can use ${ } parameter expansion to obtain different values.

Extract from the left (using #)

# deletes the shortest matching prefix (from the left, non-greedy), while ## deletes the longest matching prefix (greedy):

# Remove the first / and everything left of it → dir1/dir2/dir3/my.file.txt
echo ${file#*/}

# Remove the last / and everything left of it → my.file.txt
echo ${file##*/}

# Remove the first . and everything left of it → file.txt
echo ${file#*.}

# Remove the last . and everything left of it → txt
echo ${file##*.}

Extract from the right (using %)

% deletes the shortest matching suffix (from the right, non-greedy), while %% deletes the longest matching suffix (greedy):

# Remove the last / and everything right of it → /dir1/dir2/dir3
echo ${file%/*}

# Remove the first / and everything right of it → (empty)
echo ${file%%/*}

# Remove the last . and everything right of it → /dir1/dir2/dir3/my.file
echo ${file%.*}

# Remove the first . and everything right of it → /dir1/dir2/dir3/my
echo ${file%%.*}

Result comparison table

With file=/dir1/dir2/dir3/my.file.txt:

Expression Result
${file#*/} dir1/dir2/dir3/my.file.txt
${file##*/} my.file.txt
${file#*.} file.txt
${file##*.} txt
${file%/*} /dir1/dir2/dir3
${file%%/*} (empty)
${file%.*} /dir1/dir2/dir3/my.file
${file%%.*} /dir1/dir2/dir3/my

Memory tips

  • Look at the symbol direction: # starts trimming from the left; % trims from the right;
  • Look at the symbol count: a single symbol means “shortest match” (non-greedy), double symbols mean “longest match” (greedy);
  • Common uses: ${file##*/} gets the filename, ${file%/*} gets the directory, ${file%.*} strips the last extension, and ${file##*.} gets the extension.

Practical example

Extract the path, filename, and extension of a file in a script:

file=/var/www/html/index.php

dir=$(dirname "$file")        # /var/www/html
base=$(basename "$file")      # index.php
name=${file%.*}               # /var/www/html/index
ext=${file##*.}               # php

A deployment-oriented example

Suppose you are writing a deployment script that extracts the archive name and creates a folder for it:

archive=/data/releases/app-v1.2.3.tar.gz
base_dir=${archive%.*}
package_name=${archive##*/}
extension=${archive##*.}

mkdir -p "/data/releases/${base_dir##*/}"
echo "Package: $package_name"
echo "Extension: $extension"

A real deployment scenario: generating a target directory from an archive name

In a real release workflow, you usually deal with more than a single file. Suppose you upload an archive named /data/releases/app-service-2026.08.01.tar.gz to a server and want to extract it into a directory matching the version label while keeping the logs in the same place. This is a good case for separating the filename, parent directory, and suffix from the path:

archive=/data/releases/app-service-2026.08.01.tar.gz
version=${archive##*/}
base_name=${version%.tar.gz}
release_dir=${archive%/*}
target_dir="$release_dir/$base_name"

mkdir -p "$target_dir"
echo "Extract directory: $target_dir"

This example highlights a few practical points: first, ${archive##*/} extracts the archive name; second, ${version%.tar.gz} removes the archive suffix so the directory name is cleaner; third, ${archive%/*} keeps the parent path flexible instead of hard-coding it. That approach is reliable in CI/CD publishing, rollback jobs, and log archiving.

Troubleshooting tip: print the intermediate values

If a script behaves unexpectedly, the first thing to do is print the intermediate values before changing the logic. This is especially useful when a directory name looks wrong or an extension is extracted incorrectly:

archive=/data/releases/app-service-2026.08.01.tar.gz
echo "Original path: $archive"
echo "Filename: ${archive##*/}"
echo "Parent directory: ${archive%/*}"
echo "Without suffix: ${archive%.tar.gz}"
echo "Extension: ${archive##*.}"

This makes it easier to tell whether the issue comes from the path format, a dot in the filename, or a suffix that was matched differently.

This path-extraction technique is very useful when writing deployment scripts and log-processing scripts. For more shell scripting and server operations content, see the developer tools category, such as Linux server basics and server operations tips.

A practical combination with dirname and basename

In real scripts, path extraction is easier to maintain when it is paired with helper commands such as dirname and basename. These tools make it clearer how you are deriving a target folder, a file name, or a deployment path. For example, if you want to unpack an archive into a directory named after the package, you can extract the archive name and parent folder before creating the destination directory.

archive=/opt/releases/app-2026.08.01.tar.gz
folder=$(basename "$archive" .tar.gz)
workdir=$(dirname "$archive")

mkdir -p "$workdir/$folder"
echo "Target directory: $workdir/$folder"

Common pitfalls: trailing slashes and empty strings

Another common shell path issue is the trailing slash. Paths such as /var/www/html/ and /var/www/html may look similar, but in scripts they can produce different results when you concatenate them with other paths or when a command treats the empty string unexpectedly. A simple normalization step helps make the script more robust.

path="/var/www/html/"
path=${path%/}
[ -d "$path" ] && echo "Directory exists"

This style of scripting is common in deployment automation, log archiving, and site publishing workflows because it is easier for the next maintainer to understand than a chain of brittle string operations.

When it is worth wrapping path handling into a function

As you write more scripts, path handling logic starts to appear repeatedly. Some scripts need the directory name, others need the file name, and some need the extension or a version segment. At that point, wrapping the common logic into a small function is easier to maintain than repeatedly rewriting parameter expansion. A simple example is extracting the directory, basename, and extension through one reusable entry point.

get_path_parts() {
    local path="$1"
    echo "dir=${path%/*}"
    echo "base=${path##*/}"
    echo "ext=${path##*.}"
}

get_path_parts "/var/www/html/index.php"

This kind of small wrapper may not look impressive, but it reduces maintenance cost significantly as scripts evolve.

Original post: https://www.cnblogs.com/cqzhuomi/articles/17284324.html (cnblogs.com CQZHUOMI, repost)

Integration & Code Examples

Example 1: Parameter expansion versus basename/dirname

p=/var/log/nginx/access.log

echo "${p##*/}"     # access.log     — strip everything up to the last /
echo "${p%/*}"      # /var/log/nginx — strip the last / and after
echo "${p%.*}"      # /var/log/nginx/access
echo "${p##*.}"     # log            — extension

# equivalent with external commands, which cost a fork each
dir=$(dirname "$p"); file=$(basename "$p"); stem="${file%.*}"
printf '%s|%s|%s\n' "$dir" "$file" "$stem"

Expansions like ${var##*/} are handled inside bash with no subprocess; across tens of thousands of paths that difference is measurable.

Example 2: Precise path matching with find -path and -regex

# only entry files under releases directories
find /srv -type f -path '*/releases/*/public/index.php' -print

# extended regex: logs under cache or tmp
find /srv -type f -regextype posix-extended \
  -regex '.*/(cache|tmp)/.*\.(log|tmp)$' -print

# pull the version segment out of the full path
find /srv -type f -path '*/releases/*' -printf '%p\n' \
  | sed -E 's#.*/releases/([^/]+)/.*#\1#' | sort -u

-path matches the whole path including directories, so */releases/* expresses "at this level" better than -name; -regex must match the entire string, not a substring.

Looking Up the Expression by Need: Filename, Parent, Extension

The lookup table is easy to read and still easy to misuse in a real script, so reverse the search from the need instead. Filename is ${file##*/}, parent directory is ${file%/*}, extension is ${file##*.}, strip the extension with ${file%.*}, strip a trailing slash with ${path%/}. Those five cover most of what deployment scripts extract.

Each need also has an external-command equivalent: dirname and basename read more plainly but fork a subprocess. In a script that runs twice the difference is invisible; called once per item in a loop it accumulates into measurable runtime.

Need Parameter expansion Result for /dir1/dir2/dir3/my.file.txt External equivalent
Filename ${file##*/} my.file.txt basename "$file"
Parent directory ${file%/*} /dir1/dir2/dir3 dirname "$file"
Extension ${file##*.} txt No direct equivalent; often awk -F.
Strip the last extension ${file%.*} /dir1/dir2/dir3/my.file basename "$file" .txt needs the suffix known
Strip a trailing slash ${path%/} /var/www/html from /var/www/html/ sed 's:/*$::'

Overhead and Matching Semantics in Bulk Processing

Parameter expansion happens inside bash and starts no subprocess; dirname, basename and sed fork on every call. Over tens of thousands of paths that difference turns from negligible into most of the script's runtime, so prefer the ${} form on hot paths.

find has two matching flags with different semantics: -path matches the full path including directories, which expresses "under this level" more precisely than -name; -regex matches the whole string rather than a substring, so .*\.(log|tmp)$ needs its leading .* or the path prefix defeats the rule.

When the value to extract sits mid-path, such as a version number, parameter expansion cannot do it and a grouped sed -E replacement is needed — for example replacing .*/releases/([^/]+)/.* with \1. In those cases print the intermediate values before editing the expression; it locates the fault faster than guessing at the regex.

Limitations

  • This article reflects public information as of 2023-04-03; terms, prices and quotas follow the provider's current published terms.
  • Third-party capability and limit statements follow their official documentation; no further commitment is implied here.
  • Licensing, filing and data-residency decisions must be verified against the regulations of your operating region.

FAQ

Which is cheaper, ${file%/*} or dirname?

Use expansion: ${file%/*} runs inside bash with no fork, so /dir1/dir2/dir3/my.file.txt yields /dir1/dir2/dir3 while dirname spawns a process. Across tens of thousands of paths that gap shows up in wall time. basename still wins on odd input because it strips multi-part suffixes such as .tar.gz in a single call.

Why does ${file%%/*} return an empty string?

Because %% drops the longest suffix. /* greedily matches the whole string once the path starts with a slash. Applied to /dir1/dir2/dir3/my.file.txt nothing remains, because the longest suffix starts at the first slash. Use ${file%/*} to drop only the last slash and keep the parent path intact.

Can parameter expansion replace dirname and basename?

Yes, with caveats. ${var##/}, ${var%/} and ${var##*.} cover file name, directory and extension inside bash with no external program. dirname and basename handle trailing slashes and multi-part suffixes more gracefully: on /data/releases/app-v1.2.3.tar.gz both agree, but basename strips the whole .tar.gz in one call, which matters in minimal CI images without coreutils.

What shell does ${var##*/} require?

Any POSIX-compatible shell works: the syntax behaves identically in dash and zsh. Two traps: under set -u an unset variable exits the script, so test for emptiness first, and paths with spaces must stay quoted or the expansion looks right while the joined path splits into words. file=/dir1/dir2/dir3/my.file.txt expands the same way in dash and bash.

Related Providers

  • GitHub Actions: when the deploy script's parameter expansion has to run on CI runners and read paths from environment variables.
  • Visual Studio Code: when you debug bash parameter expansion locally and want shellcheck output inside the editor.
  • GitHub: when several people edit the script's path handling and the previous version has to stay recoverable.

Community & Resources

Official docs and communities

  • find(1) — exact semantics of -path, -regex and -printf
  • bash(1) — the parameter expansion section is the reference here
  • basename(1) — strip directory and suffix
  • dirname(1) — edge cases when taking the directory part

Learning resources and tools

  • BashFAQ — classic answers on paths and quoting
  • BashGuide — a structured tour from expansion to loops
  • sed(1) — rewriting paths with regex
  • Stack Overflow: bash — expansion, quoting and globbing in practice

Original source: cnblogs.com (CQZHUOMI) ↗