How to move files with first part as new filenamevia bash shell scripting?

I am on linux red hat, want to use the logic within bash shell script file.

I have the following type, named files in folder /staging, want to move with new filename just the firstpart upto underscore, example 20180904105056.dat, how can i get upto first part of filename and validate to chk if filename exists then append filename with sequential number at end.

if the file already exists in target folder want to append with _2, _3, _4 so on so forth.

#sample file names in source folder, these guys using space in filenames too ,
20180904105056_ss043883_prod_0defaul0000664.dat
20180904105056_ss043883_prod_0defaul0000664 2.dat

mv /staging/*.dat /targetfolder/20180904105056.dat
mv /staging/*.dat /targetfolder/20180904105056_2.dat #since here in target already filename exists.

thank you very much for the helpful info.

Try

for FN in *.dat; do echo mv $FN /targetfolder/${FN%%_*}.${FN##*.}; done

Would the --backup=numbered option to mv - should it exist on your system, which btw you do not mention - satisfy your needs?

Given that one of the sample filenames contains a <space> character (and not knowing whether or not there might be other field separators in the various parts of the real filenames that will be processed by this code) we need to add at least one pair of double-quotes and a second pair would probably be safer:

for FN in *.dat; do echo mv "$FN" "/targetfolder/${FN%%_*}.${FN##*.}"; done
1 Like