Let's suppose I have this variable:
DATE="04/Jun/2014:15:54:26"
.
Therein I need to replace /
with \/
in order to get the string:
"04\/Jun\/2014:15:54:26"
.
I tried tr
as follows:
echo "04\Jun\2014:15:54:26" | tr '\' '\\/'
But this results in: "04\Jun\2014:15:54:26"
.
It does not satisfy me. Can anyone help?
here you go:
your
tr
line was not correct, you may mis-understand whattr
does,tr 'abc' 'xyz'
will changea->x, b->y, c->z
,not changing wholeabc->xyz
..This has not been said in other answers so I thought I'd add some clarifications:
tr
uses two sets of characters for replacement, and the characters from the first set are replaced with those from the second set in a one-to-one correspondance. The manpage states thatExample:
When using
sed
for substitutions, you can use another character than '/' for the delimiter, which will make your expression clearer (I like to use ':', @n34_panda proposed '#' in their answer). Don't forget to use the/g
modifier to replace all occurences:sed 's:/:\\/:g'
with quotes orsed s:/:\\\\/:g
without (backslashes have to be escaped twice).Finally your shortest solution will probably be @Luc-Olivier's answer, involving substitution, in the following form (don't forget to escape forward slashes too when part of the expected pattern):
Use SED for substitutions:
You usually use "/" instead of the "#" but as long as it is there it doesn't matter.
I am writing this on a windows PC so I hope it is right, you may have to escape the slashes with another slash.
Sed explained, the "-e",lets you edit the file in place. You can use -i to create backup automatically.
You can also escape the slashes, with a slightly less readable solution than with hashes:
echo "04/Jun/2014:15:54:26" | sed 's/\//\\\//g'
No need to use an echo + a pipe + sed.
A simple substitution variable is enough and faster: