Filter non-alphabetic characters out of string in shell script

15,352

Solution 1

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

Solution 2

$ INPUT_STRING="ABC# .1-2-3"
$ printf '%s\n' "${INPUT_STRING//[![:alnum:]]}"
ABC123
Share:
15,352
Rich
Author by

Rich

Updated on June 23, 2022

Comments

  • Rich
    Rich almost 2 years

    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...