Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing carriage return and tab escape sequences from string in Bash

Tags:

bash

tr

Assume I have this string:

Your name is\nBobby\tBlahck\r\r

how can I remove the characters "\n, \t, \r". The string literally looks like that, it does not contain tabs or new lines. They are only characters.

When I try

echo "Your name is\nBobby\tBlahck\r\r" | tr -d '\t'

tr assumes I am trying to remove tabs, so it doesn't work and prints examtly the same string. Any ideas about how to remove them? I have the same problem with sed.

Thanks

like image 633
JohnnyLoo Avatar asked Oct 25 '25 03:10

JohnnyLoo


2 Answers

$ echo "Your name is\nBobby\tBlahck\r\r" | sed -E 's,\\t|\\r|\\n,,g'
Your name isBobbyBlahck

or

$ echo "Your name is\nBobby\tBlahck\r\r" | sed -e 's,\\[trn],,g'
Your name isBobbyBlahck

-E is on OS X; replace it with -r otherwise.

like image 54
Ewan Mellor Avatar answered Oct 26 '25 23:10

Ewan Mellor


That is because the string does not have any tab characters in it. It has a backslash followed t but no tabs:

$ echo "Your name is\nBobby\tBlahck\r\r" | tr -d '\t'
Your name is\nBobby\tBlahck\r\r

This string has a tab in it and tr removes it:

$ echo $'Your name is\nBobby\tBlahck\r\r'
Your name is
Bobby   Blahck
$ echo $'Your name is\nBobby\tBlahck\r\r' | tr -d '\t'
Your name is
BobbyBlahck

If you want special characters in bash string, use `$'...' to create them.

like image 21
John1024 Avatar answered Oct 26 '25 21:10

John1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!