Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for AWK use

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

like image 248
hummingBird Avatar asked Oct 20 '25 18:10

hummingBird


1 Answers

You may use this script:

for file in *.dat; do
   f="${file//_/-}"
   mv "$file" renamed/T-"${f#*-}"
done

You must avoid parsing output of ls command.

like image 54
anubhava Avatar answered Oct 22 '25 08:10

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!