Tech Tech
Tech Tech

Reputation: 141

Unix - How to replace invalid characters?

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

Answers (3)

jpkotta
jpkotta

Reputation: 9427

hostname=$(echo soa.ax-123 | sed s/[^a-zA-Z0-9_]/_/g)

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89584

You can use this:

echo $hostname | sed 's/\W/_/g'

Upvotes: 0

that other guy
that other guy

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

Related Questions