|
|
|
Shell provides powerful string manipulation through parameter expansion. These techniques work without calling external commands. |
|
|
String length with ${#var}: |
|
|
Bash
Substring extraction with ${var:start:length}: Note: This is bash-specific, not POSIX sh |
|
|
POSIX alternative for substrings uses expr or cut: |
|
|
Remove prefix with \({var#pattern} and \){var##pattern}: |
|
|
Remove suffix with \({var%pattern} and \){var%%pattern}: |
|
|
More practical examples: |
|
|
Extract directory and filename: |
|
|
Bash
Substitution with ${var/pattern/replacement}: |
|
|
POSIX substitution alternatives: |
|
|
Bash 4+
Case conversion (bash 4+): |
|
|
POSIX case conversion: |
|
|
String comparison: |
|
|
Check if string is empty or not: |
|
|
Check if string contains substring: |
|
|
Bash
Using [[ ]] for pattern matching: |
|
|
Using =~ for regex: |
|
|
Split string into parts: |
|
|
Bash
Join array elements: |
|
|
Trim whitespace: |
|
|
Bash
Using parameter expansion (bash): |
|
|
Repeat a string: |
|
|
String formatting with printf: |
|