Removing Fixed Prefixes and Suffixes
Often in Linux you work with file paths and extensions:| Component | Example 1 | Example 2 | Example 3 |
|---|---|---|---|
| Prefix | /home/my_username/ | /home/my_username/ | /usr/bin/ |
| Name | text_file | text_file2 | app.py |
| Suffix | .txt | .txt | .py |
${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
| Operator | Description | Example |
|---|---|---|
${var#…} | Remove shortest prefix match | Strip up to first delimiter |
${var##…} | Remove longest prefix match | Strip up to last delimiter |
${var%…} | Remove shortest suffix match | Remove first occurrence from end |
${var%%…} | Remove longest suffix match | Remove all occurrences from end |
- Use shortest‐suffix (
%) for extensions. - Use longest‐prefix (
##) for directory paths.