1

I want to change a string from

This is a string

to

This\sis\sa\sstring

but tr is not working for me no matter if I escape the \ or not

string="This is a string"
regex=$(echo "$string" | tr " " "\\s")
printf "$regex"

I just get

Thississasstring
  • With printf you always want to use the format specifier: printf "%s" "$regex" -- this ensures that any % characters in the string are not misinterpreted by printf. – glenn jackman Apr 13 '18 at 13:00
4

The main issue with your approach, I think, is that tr transliterates single characters - so even if you successfully quote '\\s' it's not going to work the way you want (it would likely just replace space with \).

In this case, you don't need external utilities at all:

string="This is a string"
echo "${string// /\\s}"
This\sis\sa\sstring

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.