Reputation: 7674
I have the following string hello/world
I want to replace the /
with -
to get hello-world
I've tried the following: http://rextester.com/NMIOL63413
$ echo hello/world | tr -c '[:alnum:]' '-'
$ hello-world-
Why is there an extra -
at the end and how to I get rid of it?
Upvotes: 2
Views: 2243
Reputation: 85800
It should be obvious that echo
prints a \n
at the end of each string. Since with the -c
, you are looking to replace characters which are not part of [:alnum:]
. Since the new-line is also not part of a valid alphanumeric character, it also gets substituted.
In such situations where you are unsure which "magical" character is present or gets substituted, do a hexdump
to see within the string. You could see the \n
at the end.
echo hello/world | hexdump -c
0000000 h e l l o / w o r l d \n
000000c
So to avoid such instances of new-line and other shell meta-characters messing with your replacement string, always use printf
:
printf '%s' 'hello/world' | tr -c '[:alnum:]' '-'
Upvotes: 7