Reputation: 814
Imagine i have file with this name:
My crazy file's "quoting" problem!.txt
If I am working in bash interactively, with TAB, bash will quote the file for me to something like this:
My\ crazy\ file\'s\ \"quoting\"\ problem\!.txt
My question is if I have that file name in a text file or saved in a variable inside a script, is there a utility to print the filename in the same quoted format? For example, if i had a text file with a bunch of file names and I wanted to print them out in the same (or at least similar functionally) way bash quotes.
I realize that file names could be massaged with sed, regexps, etc. but I was hoping to avoid the work of thinking up all the rules.
Upvotes: 0
Views: 64
Reputation: 241721
You can do it with bash's printf
using the %q
format conversion:
$ file='My crazy file'"'"'s "quoting" problem!.txt'
$ printf "%q\n" "$file"
My\ crazy\ file\'s\ \"quoting\"\ problem\!.txt
Having said that, you shouldn't really need to do that, since it would mostly be useful for use in eval
, for example, and you should probably look for an alternative. Still, if you need it, there it is.
Upvotes: 4
Reputation: 590
I can only think of something like
echo $yourvariable | sed 's/\\//g' | sed 's/^/"/g' | sed 's/$/"/g'
You may save modify/enhance this and save in your $PATH. Then you can freely access this where you have those unusual file names/string/etc;
Upvotes: 0