Batch Modifying Filenames Using Simple Brace Substitution With `bash` or `zsh`
I had downloaded a bunch of files from the internet and they all have text that I wanted to delete from the filenames. For instance the files could be a variation of “filename bank.csv
”, “filename2 bank.csv
”, etc. The bank that I downloaded the files from inserted its name in every file, and I want to delete just the bank part, leaving the rest of the filename.
I could do it manually, but why? If there is a pattern it means that the task is amenable to automation.
Initially I thought of using a sed
script and piping the filenames through the script. However, there is a better but seldom used method: brace substitution in the shell.
In bash
brace expansion takes the following pattern:
{<variable>/<pattern>/<subsitution>}
Hence in this case I’d want to use:
$ for filename in *bank*; do
> [ -f $filename ] || continue
> mv -v $filename ${filename/ bank/}
> done
What I find interesting is that scripting in the shell is really about manipulating files. So in this instance you do not even need to invoke ls
because the for
statement assumes that you want to iterate through the filenames in the current directory.
In the second line, we first test to see if any matches in the first line is a file and not a directory for instance. Then we use brace expansion/substitution to rename the file. The -v
option is just to make the mv
verbose, reporting what exactly has been changed by the script.
I could just as well replace the word bank
with something else.
zsh
In zsh
this is slightly different, and I think an improvement. Brace substitution takes a form similar to sed
, awk
, vim
etc., hence the pattern for substitution is:
{<variable>:s/<pattern>/<subsitution>}
So the above code in zsh
is:
% for filename in *bank*; do
> [ -f $filename ] || continue
> mv -v $filename ${filename:s/ bank/}
done
Now, if you have set up your zsh
history properly, the next time you download similar files from the same source, you merely need to CTRL-R
to invoke your history search and type bank
.