|
Shell provides powerful string manipulation through parameter expansion. These techniques work without calling external commands. String length with |
|
|
Output:
String: 'Hello, World!' Length: 13 |
|
|
Bash
Substring extraction with |
|
|
Output:
First 5 chars: Hello From position 7: World! Last 6 chars: World! |
|
|
POSIX alternative for substrings uses |
|
|
Output:
POSIX substring with expr: First 5: Hello Using cut: Hello |
|
|
Remove prefix with |
|
|
Output:
Path: /home/user/documents/file.txt Remove leading /: home/user/documents/file.txt Remove path (##*/): file.txt |
|
|
Remove suffix with |
|
|
Output:
Remove extension (%.*): /home/user/documents/file Directory (%/*): /home/user/documents |
|
|
More practical examples using parameter expansion. |
|
|
Output:
Filename: document.backup.tar.gz Remove .gz: document.backup.tar Remove all extensions: document Get extension: gz |
|
|
Extract directory and filename using parameter expansion. |
|
|
Output:
Path: /usr/local/bin/script.sh Directory: /usr/local/bin Filename: script.sh Basename without ext: script |
|
|
Bash
Substitution with |
|
|
Output:
Replace first: hello universe world Replace all: hello universe universe Replace at start: hi world world Replace at end: hello world planet |
|
|
POSIX substitution alternatives: |
|
|
Output:
POSIX substitution with sed: Replace first: hello universe world Replace all: hello universe universe |
|
|
Bash
Case conversion: |
|
|
Output:
Uppercase: HELLO WORLD Lowercase: hello world First char upper: Hello World First char lower: hello World |
|
|
POSIX case conversion: |
|
|
Output:
POSIX case conversion with tr: Uppercase: HELLO WORLD Lowercase: hello world |
|
|
Bash
String comparison can be done with The < syntax only works in bash. |
|
|
Output:
apple does not equal banana apple comes before banana |
|
|
Check if string is empty or not: |
|
|
Output:
empty is zero-length nonempty has content |
|
|
Check if string contains substring: |
|
|
Output:
'The quick brown fox' contains 'quick' |
|
|
Bash
Using |
|
|
Output:
Found quick |
|
|
Bash
Using |
|
|
Output:
Starts with 'The' |
|
|
Split string into parts: |
|
|
Output:
Splitting 'apple,banana,cherry': Part 1: apple Part 2: banana Part 3: cherry |
|
|
Bash
Join array elements: |
|
|
Output:
Joined: apple,banana,cherry |
|
|
Trim whitespace: |
|
|
Output:
Padded: ' hello world ' Trimmed: 'hello world' |
|
|
Bash
Using parameter expansion: |
|
|
Output:
Padded: ' hello world ' Trimmed: 'hello world' |
|
|
Repeat a string: |
|
|
Output:
Repeat '-' 20 times: -------------------- |
|
|
String formatting with |
|
|
Output:
Padded: | hello| Left: |hello | String manipulation examples complete |
|