In one folder I have a lot of audio files serialized with numbers, all of them are in mp3 format, then in the same folder I have a lot of subfolders all with numbers and slashes and subsequent characters I want to move the digitized audio files in batches to the folder starting with the corresponding number through terminal commands. At present, I use the movement of one bar, the method is as below.
mv 1.mp3 1-*
mv 2.mp3 2-*
mv 3.mp3 3-*
mv 4.mp3 4-*
mv 5.mp3 5-*
mv 6.mp3 6-*
mv 7.mp3 7-*
mv 8.mp3 8-*
mv 9.mp3 9-*
mv 10.mp3 10-*
mv 11.mp3 11-*
mv 12.mp3 12-*
mv 13.mp3 13-*
mv 14.mp3 14-*
mv 15.mp3 15-*
mv 16.mp3 16-*
mv 17.mp3 17-*
mv 18.mp3 18-*
mv 19.mp3 19-*
mv 20.mp3 20-*
mv 21.mp3 21-*
mv 22.mp3 22-*
mv 23.mp3 23-*
Is there a way to do it with a single code?
CodePudding user response:
for file in *.mp3; do
b="${file%.mp3}"
for d in "$b"-*; do
mv "$file" "$d"
break
done
done
The inner loop is to ensure that the wildcard expands to exactly one match, or else to move into the first of the matches. You might also want to ensure that the destination is a directory.
CodePudding user response:
You can do it without inner loops:
for mp3 in *.mp3; do
subdir=( ${mp3%.*}-* ) # Create array of subdirs if there are many
[[ -d $subdir ]] && mv "$mp3" "$subdir/" # Check if $subdir exists than mv
done
You can also loop over subdirs instead of .mp3:
for subdir in *[0-9]-*; { mv "${subdir%-*}.mp3" "$subdir"; }