I'm looking for something that will translate a string as follows, using only bash / standard Linux commands:
- Single-quotes surrounding a string should be removed
- Double-quotes surrounding a string should be removed
- Unquoted strings should remain the same
- Strings with unmatched surrounding quotes should remain the same
- Single-quotes that don't surround the string should remain
- Double-quotes that don't surround the string should remain
For example:
- 'Food' should become Food
- "Food" should become Food
- Food should remain the same
- 'Food" should remain the same
- "Food' should remain the same
- 'Fo'od' should become Fo'od
- "Fo'od" should become Fo'od
- Fo'od should remain the same
- 'Fo"od' should become Fo"od
- "Fo"od" should become Fo"od
- Fo"od should remain the same
Thank you!
This should do it:
Where in.txt is:
And expected.txt is:
You can check they match with:
Just stumbled upon this as well. For the first three test cases,
eval echo $string
works well. To get it to work for all cases requested and a few others, I came up with this (tested withbash
anddash
):You probably want to use sed...
You could use
tr
:... also works, however 'tr' is known to be problematic on much older (circa Redhat 9-ish) distributions.
tr
is an abbreviation for 'translate', commonly used in pipes to transform input. The-d
option simply means 'delete'.Most modern versions also contain predefined macros to transform upper to lower, lower to upper, kill white space, etc. Hence, if you use it, take a second to poke at what else it does (see the help output / man page), comes in handy.
Explanation: Since quotes are already understood by the shell you can ask the shell to evaluate a command that just echos the quoted string, the same way it does when you type it yourself.
Here,
eval echo $VAR
expands toeval echo 'FOOD'
because the quotes are actually part of the value ofVAR
. If you were to runecho 'FOOD'
into the shell you'd getFOOD
(without the quotes). That's whateval
does: it takes its input and runs it like a shell command.it doesn't handle edge cases extremely well (such as an empty string), but it will serve as a starting point. It works by striping the front and back character if they are the same and if they are ' or "