Reputation: 141
I a writing unix bash shell script.
I want to replace all invalid characters in a text with underscore("_"). My valid characters list is a-z, A-Z, "_" and 0-9. Basically it is alphanumeric and _. In the below example
#!/bin/bash
hostname=soa.ax-123
I want the variable hostname value to be replaced as soa_ax_123
Can anyone help me to write the login to find and replace the invalid characters with "_"
Thanks in advance chris
Upvotes: 2
Views: 1650
Reputation: 123570
You can do pattern substitution in parameter expansion:
#!/bin/bash
hostname=soa.ax-123
newhostname=${hostname//[^a-zA-Z_0-9]/_}
echo "The fixed hostname is $newhostname"
Upvotes: 10