Skip to content

Instantly share code, notes, and snippets.

@dave-burke
Last active June 24, 2023 03:54
Show Gist options
  • Save dave-burke/9766a2f398e2bd08625b to your computer and use it in GitHub Desktop.
Save dave-burke/9766a2f398e2bd08625b to your computer and use it in GitHub Desktop.
Demo of string manipulation in Bash
#!/bin/bash
# based on http://www.tldp.org/LDP/abs/html/string-manipulation.html
test=abcABC123ABCabc
echo "\${test} = ${test}"
echo && echo "Substrings:\${test:pos:length}"
echo "\${test:3} = ${test:3}" # ABC123ABCabc
echo "\${test: -3} = ${test: -3} " # abc
echo "\${test:3:3} = ${test:3:3}" # ABC
echo "\${test: -4:3} = ${test: -4:3}" # Cab
echo && echo "Front substring removal: \${test#pattern}"
echo "\${test#a*C} = ${test#a*C} (shortest match)" # 123ABCabc
echo "\${test##a*C} = ${test##a*C} (longest match)" # abc
echo && echo "Back substring removal: \${test%pattern}"
echo "\${test%C*c} = ${test%C*c} (shortest match)" # abcABC123AB
echo "\${test%%C*c} = ${test%%C*c} (longest match)" # abcAB
echo && echo "Substring replacement: \${test/find/replace}"
echo "\${test/abc/xyz} = ${test/abc/xyz} (first instance)" # xyzABC123ABCabc
echo "\${test//abc/xyz} = ${test//abc/xyz} (all instances)" # xyzABC123ABCxyz
echo "\${test/#abc/xyz} = ${test/#abc/xyz} (front only)" # xyzABC123ABCabc
echo "\${test/%abc/xyz} = ${test/%abc/xyz} (back only)" # abcABC123ABCxyz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment