Issue
I want to replace special characters (regex \W) with _ (underscore) But I don't want to replace whitespace with underscore Also replace multiple consecutive special characters with single underscore
Example
String: The/Sun is red@
Output: The_Sun is red_
String: .//hack Moon
Output: _hack Moon
I have tried echo 'string' | sed 's/\W/_/g'
But it's not accurate
Solution
sed
approach:
s="The/Sun is red@ .//hack Moon"
sed -E 's/[^[:alnum:][:space:]]+/_/g' <<<"$s"
The_Sun is red_ _hack Moon
[^[:alnum:][:space:]]+
- match any character sequence except alphanumeric and whitespace
Answered By - RomanPerekhrest Answer Checked By - Pedro (WPSolving Volunteer)