Reputation: 2215
I´m a nooby in regex so i have my headache with sed. I need help to replace all special characters from the given company names with "-".
So this is the given string:
FML Finanzierungs- und Mobilien Leasing GmbH & Co. KG
I want the result:
FML-Finanzierungs-und-Mobilien-Leasing-GmbH-&-Co-KG
I tried the following:
nr = $(echo "$name" | sed -e 's/ /-/g'))
so this replace all whitespaces with -
, but what the right expression to replace the others? My one search via google are not very successful.
Upvotes: 0
Views: 353
Reputation: 5092
Try this way also
echo "name" | sed 's/ \|- \|\. /-/g'
OutPut :
FML-Finanzierungs-und-Mobilien-Leasing-GmbH-&-Co-KG
Upvotes: 1
Reputation: 44023
That depends on what you consider to be a special character -- I say this because you appear to consider &
a regular character but not .
, which seems a bit odd. Anyway, I imagine something of the form
nr=$(echo "$name" | sed 's/[^[:alnum:]&]\+/-/g')
would serve you best. Here [^[:alnum:]&]
matches any character that is not alphanumeric or &
, and [^[:alnum:]&]\+
matches a sequence of one or more such characters, so the sed
call replaces all such sequences in $name
with a hyphen. If there are other characters that you consider regular, add them to the set. Note that the handling of umlauts and suchlike depends on your locale.
Also note that echo
may cause trouble if $name
begins with a hyphen (it could be parsed as options for echo
), so if you can tether yourself to bash
,
nr=$(sed 's/[^[:alnum:]&]\+/-/g' <<< "$name")
might be more robust.
Upvotes: 2
Reputation: 41446
Do this help you:
awk -vOFS=- '{gsub(/[.-]/,"");$1=$1}1' <<< "$name"
FML-Finanzierungs-und-Mobilien-Leasing-GmbH-&-Co-KG
gsub(/[.-]/,"")
Removes .
and _
-vOFS=-
sets new field separator to -
$1=$1
reconstruct the line so it uses new field separator
1
print the line.
To get it to a variable
nr=$(awk -vOFS=- '{gsub(/[.-]/,"");$1=$1}1' <<< "$name")
Upvotes: 1
Reputation: 289495
Apparently you wan to remove -
and .
and then replace spaces with -
.
This would do it, by saying sed -e 'one thing' -e 'another thing'
:
$ echo "$name" | sed -e 's/[-\.]//g' -e 's/ /-/g'
FML-Finanzierungs-und-Mobilien-Leasing-GmbH-&-Co-KG
Note we enclose within square backets all the characters that we want to treat equally: [-\.]
means either -
or .
(we need to escape it, otherwise it would match any character).
Upvotes: 1