Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hi Mislav,
During our interview, I mentioned some uses of the Linux shell that
twisted my brain. Here's a script demonstrating two of them: process
substitution and piping to bash.
This script prints commands to rename the files provided on the
command line. The new names will be consecutive integers: 1, 2, 3, 4...
The script is safe to run -- it makes no modifications to your system.
It uses process substitution <() to produce the "mv" commands on
stdout. Optionally, you can pipe the output of the script to bash to
run the "mv" commands.
To run:
$ touch one two three four five
$ ./name2number one two three four five
and optionally,
$ ./name2number one two three four five | bash
You'll need the "seq" command installed on your system. I don't know
if it's installed by default.
Dan
------------8<----------------- cut here ----------------8<------------------
#!/bin/bash
# name2number: rename files as numbers
PROG=$(basename $0)
if [ $# -lt 1 ]
then
echo "Usage: $PROG [files]"
echo "Prints 'mv' commands to rename files by number (1, 2, 3, ...)."
echo "The files must exist."
echo "Pipe the output to bash to execute the commands."
exit 1
fi
# List of targeted files, one per line, with proper escaping to handle
# filenames with spaces and quotes in them.
files=$(/bin/ls -1d "$@" | sed -e 's/"/\\\"/g' -e 's/^/"/' -e 's/$/"/')
# Generate "mv" commands from the file list
paste <(echo "$files") <(seq -w $(echo "$files" | wc -l)) | sed 's/^/mv /'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment