Search code examples
bashshellquoting

Rename all files including a bracket (


I have a directory filled with a lot of files, some of which have brackets in them; e.g. a(file).ext,an(other)file.ext, etc. My goal is to rename them into something like this: a_file_.ext or an?other?file.ext. (doesn't matter what character).

the reason for this is because certain console applications can't deal with these brackets and think it's some kind of command.

things I already tried:

$ rename ( ? *(*
$ for f in *(*; do mv $f ${f//(/?}; done
$ for f in "*(*"; do mv $f ${f//\"(\"/\"?\"}; done

and the like. It could be that I'm not understanding these rename functions. (I do know that these only work for "(" and that I have to do them again for ")") So could someone also give some more explanation about it's syntax and why it won't work?

All in Bash.


Solution

  • Consider:

    (shopt -s nullglob; for f in *[\(\)]*; do mv "$f" "${f//[()]/_}"; done)
    
    • ( and ) are syntax, and need to be escaped to be unambiguously referred to as literals.
    • Setting the nullglob option makes the glob expand to nothing at all, rather than itself, if no files match. Putting the code in a subshell prevents this configuration change from persisting beyond the single command.
    • Using quotes around expansions is mandatory if you don't want those expansions to be subject to string-splitting and globbing.