Deleting characters matching a pattern

Bash:
Deleting characters matching a pattern

How to:

Delete leading/trailing whitespace:

text="   Hello, World!   "
trimmed=$(echo "$text" | xargs)
echo "$trimmed"

Output: Hello, World!

Remove all digits:

text="B4sh i5 amaz1ng!"
cleaned=${text//[^a-zA-Z ]/}
echo "$cleaned"

Output: Bsh i amazng

Replace specific characters:

text="Hello-World!"
cleaned=${text//-/_}
echo "$cleaned"

Output: Hello_World!

Deep Dive

In the beginning, text processing tools like sed and awk were the go-to for string manipulation. Bash has since incorporated pattern matching and string manipulation directly into the shell itself, giving its users plenty of power without the need for external commands.

The ${parameter/pattern/string} syntax is one approach where you replace first match of pattern with string. To remove all matches, just add another / as shown in the above examples.

Alternatives include using classic UNIX tools like sed, awk, tr, or more modern scripting languages such as Python or Perl.

Under the hood, Bash uses globbing and wildcards for pattern matching, but when you see those ${text//pattern/} constructs, you’re dealing with Bash’s parameter expansion—a feature that’s mighty handy for string manipulation.

See Also