Say I have an unorganized directory with thousands of files that have prefix in their names like abc-tab, abc-vib, h12-123, h12-498.... How do I move files with the same prefix into their own directory?
I was thinking about using something like
find . -path '*/support/*abc*' -exec mv "{}" /new/abc\;
But this means I will have to retype the command for every prefix.
Grab all the prefixes with ls and uniq to get a single list, then move the files using a for loop.
for F in $(ls | cut -d- -f1 | uniq); do
    mkdir "${F}" && mv "${F}"-* "${F}"
done
Many people learn shell scripting from the Advanced Bash Scripting Guide. Check out the cut and uniq man pages for details on those programs.
I'd use a for loop to operate on each instance of each filename.
From within the directory containing the files:
    mkdir newfolder
    for i in prefix_*
    do
       cp $i newfolder/$i
    done
Then I'd check that the right files copied over, and if so run
    rm prefix_*
The more dangerous approach would be to run
    mkdir newfolder
    for i in prefix_*
    do
       mv $i newfolder/$i
    done
But mv will automatically remove the source files, and I like to ensure the correct actions happened before that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With