Please use ***
[code][/code] tags*** around your code and data, to preserve formatting and to improve readability. Please do
not use quote tags, colors, or other fancy formatting.
The main problem here is that the shell sees quotes as part of its syntax, and parses them before the command is run. You need to "quote the quotes", or otherwise escape them so that the values you need are passed to
tr.
http://mywiki.wooledge.org/Arguments
http://mywiki.wooledge.org/WordSplitting
http://mywiki.wooledge.org/Quotes
Some key points to remember are:
- Inside single-quotes, every character is escaped (except another single-quote).
- Inside double-quotes, every character is escaped, except for $,`,\, (and ! when history expansion is enabled.), and of course the closing double-quote.
- Single-quotes escape double-quotes, and double-quotes escape single-quotes.
- Inside double-quotes, the backslash (\) can be used to escape the few characters that are still considered special, plus the newline and the double-quote itself (\$, \`, \\, \!, \n, \").
- Outside of any quotes, a backslash will escape all characters.
- The ansi-c quoting pattern ($'') can be used to expand backslash escaped characters of various kinds, including both styles of quotes. (This is not supported by all shells).
See the bash man page QUOTING section for details
So lets say you want to use
tr to invert both types of quotes at the same time, for example. From the above, we can see that there are several options available to you. The easiest methods would probably use #5 or #6, otherwise it gets kind of tricky and less readable.
Code:
tr \'\" \"\' <infile #changes ' to " and " to '
tr $'\'"' $'"\'' <infile #the same, using ansi-c quoting, backslashing the literal singles
tr "'"'"' '"'"'" <infile #using one kind of quote to escape the other
tr "'\"" "\"'" <infile #using double-quotes, and backslashing literal doubles in them
The same works in sed and any other command, of course. BTW, if we were using sed, the "
y" operator, equivalent to
tr, would be more appropriate here.
Code:
sed $'y/\'"/"\'/' infile #using ansi-c quoting
But why bother, usually, when you have
tr itself? It's lighter and faster.