Ubuntu – Move Multiple Files To Multiple Folders Based on Names of Files


I have a bunch of files in one folder named numeric as 001001 .. 001002 .. 002001 .. 002002 .. and so on until 114001 .. 114002 , i want to move every group of files that start with the same number to one folder , all files with 001 to folder 1 , all files with 110 to folder 110 and so on , no problem in creating the folders i have a problem in moving files in the sub folders in one step , hope some one help me to do that

Best Answer

Seems like the main trick here is translating the file name into the target folder name. There are two steps: truncate all but the first three digits, and remove zero padding. For this I have selected the sed and $((10# commands respectively:

for X in *; do mv $X $((10#$(echo $X | sed -e 's/^\(...\).*/\1/') )); done

This gives me minor errors such as mv: cannot move ‘114’ to a subdirectory of itself, ‘114/114’, but presumably you will not care about that if your files are getting moved where you want them to go.