Pretty much every day, I discover something about ‘Unix’ that totally blows my mind, even though I’ve been using it for 25 years. Today, it was renaming a file:
mv /a/file/with/a/very/long/path/name /a/file/with/a/very/long/path/different-name
I’m sure that, like me, you’ve done this many times, silently cursing the mv
command as you do it. Maybe you’re an expert copy/paster, maybe you resort to
cding all over the place.
I even briefly considered writing a short script that would let me do something like this:
change /a/file/with/a/very/long/path/name different-name
(I know there’s a popular rename tool, but I don’t think even that program lets me do this quite as easily as I’d like)
Fortunately, that’s unnecessary. All that’s required is a basic understanding of Bash brace expansion:
mv /a/file/with/a/very/long/path/{name,different-name}
While I don’t like that syntax quite as much as the simple, hypothetical
change, it goes far beyond this one use and it’s clearly worth getting
acquainted with.
The beauty of this expansion is that it treats the /a/file/... bit as a prefix,
that gets repeated for each expansion, so the above command gets literally
replaced with:
mv /a/file/with/a/very/long/path/name /a/file/with/a/very/long/path/different-name
I.e. exactly where we started.
Finally, if I can remember it, I have a fix for the bad old way I’ve been renaming files for a quarter of a century. Roll on tomorrow’s lesson!