Removing carriage return and tab escape sequences from string in Bash

9.4k views Asked by At

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

4

There are 4 answers

0
Ewan Mellor On BEST ANSWER
$ 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.

0
John1024 On

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.

7
auth private On

sed -e 's/[\\\][t]//g' -e 's/[\\\][n]//g' -e 's/[\\\][r]//g'

another answer too

sed -e 's/\\[[a-z]]*//g'

0
bedwyr On

Use a character group to check what's following the '\':

echo "Your name is\nBobby\tBlahck\r\r" | sed -r 's/\\[nrt]/ /g'