Last week, I needed to prefix all files in a directory with a given string. A real-world example would be to say you have to move all your source files to "backup-{filename}.cpp" or something to that effect. One could run mv file1.cpp backup-file1.cpp``mv file2.cpp backup-file2.cpp ... mv filen.cpp backup-filen.cpp, but that is very tedious and takes entirely too long. In the time I would have taken to move all the files I needed to, I created the following Bash script to do it for me:
#!/bin/bash
# Usage: prefix
PATTERN=
PREFIX=
if [ -z $1 ]
then
echo "No prefix given! Exiting ..."
exit 0
else
PREFIX="$1"
fi
if [ -z $2 ]
then
# No regex pattern given; do nothing
echo "No pattern given; using all files in directory..."
else
PATTERN="$2"
fi
for word in `ls ${PATTERN}`
do
`mv "${word}" "${PREFIX}${word}"`
echo "moved "${word}" to "${PREFIX}${word}""
done
exit 0
Copy-and-paste the following code into a /usr/bin/prefix, then chmod +x /usr/bin/prefix (as root). From there, you can call the script in the following ways:
Move all .cpp files to backup-.cpp:
prefix backup- *.cpp
Move all files to backup-{filename}
prefix backup-
Move all files to "project backup-{filename}"
prefix "project backup-"
This could probably be simplified into a one-line perl script, but I'll take the verbosity and readability over the leetness factor of being able to do it in a single line. That would be pretty cool, though. Perhaps a revised script is in order ...