Phillip T. Phillip T. - 1 year ago 70
Bash Question

Shell Scripting: Convert file string to be usable in a command

I'm stuck on figuring out a way to take text of a file name and converting it into a string that can be usable in commands.

I would like to take a file name (for example:

[foo] bar - foo.mkv
) and add backslashes to spaces, square brackets, and any other characters (for example
\[foo\]\ bar\ -\ foo.mkv
) so that they are usable in a command such as

Thank you for helping me.

Answer Source

I don't think there is a need for that. You could enclose the filename variable in double quotes and the commands would handle the rest.

$ touch "[foo] bar - foo.mkv"
$ ls
[foo] bar - foo.mkv
$ mv "[foo] bar - foo.mkv" "abcd"
$ ls

So just enclose the string in double quotes and it must solve your problem:

mv "$oldname" "$newname"

There's rarely a need, but if you want to have substitutions you can use this:

$ printf '%q' "[foo] bar - foo.mkv"
\[foo\]\ bar\ -\ foo.mkv
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download