Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter non-alphabetic characters out of string in shell script

Very simple question but can't seem to find a simple answer...

I am writing a bash script which needs to remove all non-alphabetic and non-numeric characters. Eg. I want...

INPUT_STRING="ABC# .1-2-3"

OUTPUT_STRING= # some form of processing on $INPUT_STRING #

echo $OUTPUT_STRING
ABC123

I realize that this would be best solved using regex, but not sure how to use this effectively in the script.

All help greatly appreciated...

like image 282
Rich Avatar asked Jun 18 '13 11:06

Rich


1 Answers

You can use sed to strip all chars that are not a-z, A-Z or 0-9:

$ echo "ABC# .1-2-3" | sed 's/[^a-zA-Z0-9]//g'
ABC123

So in your case,

$ INPUT_STRING="ABC# .1-2-3"
$ OUTPUT_STRING=$(echo $INPUT_STRING | sed 's/[^a-zA-Z0-9]//g')
$ echo $OUTPUT_STRING
ABC123
like image 182
fedorqui 'SO stop harming' Avatar answered Oct 13 '22 19:10

fedorqui 'SO stop harming'