Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux find files with similar name and move to new directory [closed]

Tags:

linux

bash

shell

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.

like image 830
user2189312 Avatar asked Nov 01 '25 04:11

user2189312


2 Answers

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.

like image 141
andrewdotn Avatar answered Nov 04 '25 03:11

andrewdotn


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.

like image 30
CaffeineConnoisseur Avatar answered Nov 04 '25 03:11

CaffeineConnoisseur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!