JohnnyLoo
JohnnyLoo

Reputation: 927

Removing carriage return and tab escape sequences from string in Bash

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

Upvotes: 4

Views: 10607

Answers (4)

auth private
auth private

Reputation: 1314

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

another answer too

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

Upvotes: -1

Ewan Mellor
Ewan Mellor

Reputation: 6857

$ 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.

Upvotes: 2

bedwyr
bedwyr

Reputation: 5904

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

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

Upvotes: 1

John1024
John1024

Reputation: 113984

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.

Upvotes: 1

Related Questions