remove control characters from string using TR
Asked Answered
T

2

7

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

Typesetter answered 11/8, 2020 at 6:28 Comment(0)
I
19

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

Interlinear answered 11/8, 2020 at 6:33 Comment(1)
You can also delete both parenthesis characters with a single run of tr -d '()'Anna
S
1

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
Spellbound answered 11/8, 2020 at 14:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.