0
0
Bash Scriptingscripting~5 mins

String suffix removal (${var%pattern}) in Bash Scripting

Choose your learning style9 modes available
Introduction

This helps you cut off the ending part of a word or sentence stored in a variable. It is useful when you want to remove a known ending.

You have a filename with extension and want just the name without the extension.
You want to remove a trailing slash from a folder path.
You want to get the base name from a URL by removing the last part.
You want to clean up user input by removing a known suffix.
Syntax
Bash Scripting
${variable%pattern}

The % removes the shortest match of pattern from the end of the variable's value.

Use %% to remove the longest match from the end.

Examples
Removes the suffix .txt from the filename, leaving just report.
Bash Scripting
filename="report.txt"
name=${filename%.txt}
Removes the trailing slash from the path.
Bash Scripting
path="/home/user/docs/"
clean_path=${path%/}
Removes the .html suffix from the URL string.
Bash Scripting
url="example.com/page.html"
base=${url%.html}
Sample Program

This script removes the .jpeg suffix from the filename and prints both original and base name.

Bash Scripting
#!/bin/bash

file="photo.jpeg"

# Remove the shortest suffix matching .jpeg
base_name=${file%.jpeg}

echo "Original file: $file"
echo "Base name: $base_name"
OutputSuccess
Important Notes

If the pattern does not match the end of the string, the variable remains unchanged.

Patterns use shell globbing, so * and ? can be used.

Summary

${var%pattern} removes the shortest matching suffix from a variable.

It is useful for trimming file extensions or trailing characters.

Use %% for the longest match removal.