#FYI Rename Files Quicker in Linux

Using brace expansion - quickly rename, move, copy files with this shorthand syntax. Supported by most terminals, you can even generate a set of dummy files.

#FYI Rename Files Quicker in Linux
Photo by Alex Chumak / Unsplash

How often have we had to temporarily create a backup, or just save a copy, perhaps just move out a file. You may need to rename index.html to index.html.bak
And maybe even rename it back to index.html?

The usual approach

mv /var/www/vhosts/gridiron.dev/httpdocs/index.php /var/www/vhosts/gridiron.dev/httpdocs/index.php.bak
mv /apps/app.py  /apps/module.py

Here's a quicker way to do this

mv /var/www/vhosts/gridiron.dev/httpdocs/index.php{,.bak}
mv /apps/app.py{bak,}

The general syntax being mv path+filename{preamble,postscript}

Where, preamble = current, postscript to new

Explanation

This is possible if your terminal supports(and it usually does) brace expansion.

Brace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is similar to filename expansion (see Filename Expansion), but the filenames generated need not exist. Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma-separated strings or a sequence expression between a pair of braces, followed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right.
Brace Expansion (Bash Reference Manual)
Brace Expansion (Bash Reference Manual)

Copying Files

The same approach works for when you need to make a copy of a file as well.

Create a dummy file and list the directory contents

touch README.md
-rw-r--r--  1 tgid  staff     0B Nov 15 10:04 README.md

Make a copy of the file created previously, and add a new extension

cp -v README.md{,.bak}
README.md -> README.md.bak

-rw-r--r--  1 tgid  staff     0B Nov 15 10:04 README.md
-rw-r--r--  1 tgid  staff     0B Nov 15 10:05 README.md.bak

Bonus

Looking to experiment with command line tricks? Or just need a set of dummy files? Use ranges and brace expansion together

touch employee-{1..10}.log

-rw-r--r--  1 tgid  staff     0B Nov 15 10:13 employee-1.log
-rw-r--r--  1 tgid  staff     0B Nov 15 10:13 employee-10.log
-rw-r--r--  1 tgid  staff     0B Nov 15 10:13 employee-2.log
-rw-r--r--  1 tgid  staff     0B Nov 15 10:13 employee-3.log
-rw-r--r--  1 tgid  staff     0B Nov 15 10:13 employee-4.log
-rw-r--r--  1 tgid  staff     0B Nov 15 10:13 employee-5.log
-rw-r--r--  1 tgid  staff     0B Nov 15 10:13 employee-6.log
-rw-r--r--  1 tgid  staff     0B Nov 15 10:13 employee-7.log
-rw-r--r--  1 tgid  staff     0B Nov 15 10:13 employee-8.log
-rw-r--r--  1 tgid  staff     0B Nov 15 10:13 employee-9.log