Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove control characters from string using TR

Please try the following commands:

echo "(After Sweet Memories) Play Born To Lose Again" | tr '(' '-' | tr ')' '-' | tr ' ' '-'

-After-Sweet-Memories--Play-Born-To-Lose-Again (notice the double --)

I'm unable to modify the command and pass a (null) value instead i have to pass another -

see this example and this error:

echo "(After Sweet Memories) Play Born To Lose Again" | tr '(' '' | tr ')' '' | tr ' ' '-'

tr: tr: when not truncating set1, string2 must be non-emptywhen not truncating set1, string2 must be non-empty

like image 413
Ian Arman Avatar asked Jan 25 '23 20:01

Ian Arman


2 Answers

You can use "tr -d" to just remove chars. Is this the solution you are searching for?

echo "(After Sweet Memories) Play Born To Lose Again" | tr -d '(' |  tr -d ')' |  tr ' ' '-'

After-Sweet-Memories-Play-Born-To-Lose-Again

like image 94
Jonatan Avatar answered Jan 27 '23 09:01

Jonatan


A tr solution has been provided, but tr requires you run multiple instances in a pipeline. You can do it all in one process with sed.

echo "(After Sweet Memories) Play Born To Lose Again" | sed 's/ /-/g; s/[()]//g;'
After-Sweet-Memories-Play-Born-To-Lose-Again

You can even lose the echo (though that's hardly an issue...)

sed 's/ /-/g; s/[()]//g;' <<< "(After Sweet Memories) Play Born To Lose Again"
After-Sweet-Memories-Play-Born-To-Lose-Again
like image 26
Paul Hodges Avatar answered Jan 27 '23 08:01

Paul Hodges