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.
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