0
0
Bash Scriptingscripting~5 mins

String prefix removal (${var#pattern}) in Bash Scripting

Choose your learning style9 modes available
Introduction
This helps you quickly remove a part from the start of a text stored in a variable. It is useful when you want to clean or shorten text without changing the original.
You have a file path and want to remove the folder part to get just the file name.
You receive a string with a fixed prefix and want to remove that prefix.
You want to trim a known pattern from the start of a string before processing it.
You are parsing logs and want to remove timestamps or tags at the beginning.
Syntax
Bash Scripting
${variable#pattern}
The # removes the shortest match of the pattern from the start of the variable's value.
Use ## to remove the longest match instead.
Examples
Removes the '/home/user/' prefix from the path, leaving 'file.txt'.
Bash Scripting
filename="/home/user/file.txt"
basename=${filename#"/home/user/"}
echo "$basename"
Removes 'https://' from the start of the URL.
Bash Scripting
url="https://example.com/page"
clean_url=${url#"https://"}
echo "$clean_url"
Removes the shortest 'abc' from the start, resulting in '123abc'.
Bash Scripting
text="abc123abc"
result=${text#abc}
echo "$result"
Sample Program
This script removes the '/var/log/' prefix from the full path to get just the file name.
Bash Scripting
#!/bin/bash

full_path="/var/log/syslog"

# Remove the directory path, keep only the file name
file_name=${full_path#"/var/log/"}

echo "Full path: $full_path"
echo "File name only: $file_name"
OutputSuccess
Important Notes
If the pattern does not match the start, the variable remains unchanged.
Patterns support wildcards like * and ? for flexible matching.
Use double quotes around variables to avoid word splitting or globbing issues.
Summary
Use ${var#pattern} to remove the shortest matching prefix from a variable's value.
It is useful for cleaning or extracting parts of strings in scripts.
Remember to use quotes to keep your script safe and predictable.