I'd love to have a more elegant solution for a mass rename of files, as shown below. Files were of format DEV_XYZ_TIMESTAMP.dat
and we needed them as T-XYZ-TIMESTAMP.dat
.
In the end, I copied them all (to be on the same side) into renamed
folder:
ls -l *dat|awk '{system("cp " $10 " renamed/T-" substr($10, index($10, "_")+1))}'
So, first I listed all dat files, then picked up 10th column (file name) and executed a command using awk's system function. The command was essentially copying of original filename into renamed folder with new file name. New file name was created by removing (awk substring function) prefix before (including) _ and adding "T-" prefix.
Effectively:
cp DEV_file.dat renamed/T-file.dat
Is there a way to use cp
or mv
together with some regex rules to achieve the same in a bit more elegant way?
Thx
This is how I would do it:
cpdir=renamed
for file in *dat; do
newfile=$(echo "$file" | sed -e "s/[^_]*/T/" -e "y/_/-/")
cp "$file" "$cpdir/$newfile"
done
The sed
scripts transforms every non-underscore leading characters in a single T and then replaces every _
with -
. If cpdir
is not sure to exist before execution, you can simply add mkdir "$cpdir"
after first line.