Monday, October 17, 2011

Bash substring exclusive replacement

This is a neat little trick I figured out today. I needed to remove all characters from a variable that were not digits or spaces. I've done a lot of variable manipulation in bash, but nothing with more than one condition.

It turns out that you can negate with the ^ character, combined with the | "or" character to get this:
$ MYVAR="4322, #32"
$ echo ${MYVAR//[^[:digit:]|[:space:]]/}
4322 32

No comments:

Post a Comment