Skip to main content
In Part One, we covered basic parameter‐expansion techniques for stripping fixed prefixes or suffixes. Here, we’ll explore more flexible patterns using wildcards to handle arbitrary extensions, path segments, or words in a string.

Removing Fixed Prefixes and Suffixes

Often in Linux you work with file paths and extensions: A fixed‐suffix removal like ${var%.txt} only matches when the filename actually ends in .txt:
Using ${var%.txt} leaves .py files untouched. For arbitrary extensions or dynamic patterns, you’ll need wildcards.

Using Wildcards for General Cases

By introducing * in the pattern, you can remove everything up to or after a delimiter (space, slash, dot, etc.).

Strip the First Word

For a space-separated string, ${var#* } removes the shortest match from the front (everything up to the first space):

Strip the Last Word

Using ${var% *} removes the shortest match from the end (from the last space onward):
Always pair * with a literal character (e.g., space or slash). A pattern like ${var%*} matches the entire string, returning an empty result.

Handling Unix‐Style Filenames

Consider two variables:
  • Prefix: directory path
  • Name: file name
  • Suffix: extension

Remove All Directory Components

  • ${var#*/} strips up to the first slash
  • ${var##*/} strips up to the last slash (longest‐prefix removal)

Strip File Extension

Use shortest‐suffix (%) or longest‐suffix (%%). With a single dot, both behave identically:

Choosing the Right Operator

  • Use shortest‐suffix (%) for extensions.
  • Use longest‐prefix (##) for directory paths.
With these four operators, you can tailor string manipulations to filenames, paths, or any delimited data.

Watch Video

Practice Lab