0

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 mv.

Thank you for helping me.

1
  • 2
    You do not need to do this, your file name is 100% usable as is, you just need to quote it when you use it just like you should quote ALL shell variables unless you have a specific purpose in mind by not doing so. Commented Oct 31, 2016 at 2:06

1 Answer 1

4

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
abcd

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.