Skip to content

Instantly share code, notes, and snippets.

@24HOURSMEDIA
Created November 3, 2018 21:10
Show Gist options
  • Save 24HOURSMEDIA/dae8bd4d8db7467144102a9ed6555371 to your computer and use it in GitHub Desktop.
Save 24HOURSMEDIA/dae8bd4d8db7467144102a9ed6555371 to your computer and use it in GitHub Desktop.
normalize a string in bash to uppercase with underscores examples
#!/bin/bash
## Convert 'this/is a:string 123' to THIS_IS_A_STRING_123
##
# converting a hard coded string to all uppercase with underscoree
echo "this/is a:string 123" | iconv -t ascii//TRANSLIT | sed -r s/[^a-zA-Z0-9]+/_/g | sed -r s/^-+\|-+$//g | tr a-z A-Z
# output: THIS_IS_A_STRING_123
# using variables variable
STRING='this/is a:string 123'
STRING2=$(echo $STRING | iconv -t ascii//TRANSLIT | sed -r s/[^a-zA-Z0-9]+/_/g | sed -r s/^-+\|-+$//g | tr a-z A-Z)
echo $STRING2;
# output: THIS_IS_A_STRING_123
# with a function
uppify () {
echo $(echo $1 | iconv -t ascii//TRANSLIT | sed -r s/[^a-zA-Z0-9]+/_/g | sed -r s/^-+\|-+$//g | tr a-z A-Z)
}
STRING='this/is a:string 123'
uppify "$STRING";
# output: THIS_IS_A_STRING_123
RESULT=$(uppify "$STRING")
echo result is $RESULT
# output: resul is THIS_IS_A_STRING_123
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment