Search code examples
bashdirectorymv

Remove a file from a folder to its name (bash)


I have several folders with names like:

  • 4553, 6723, 7765.

Inside I have a file with the same name in pdf:

  • 4553.pdf, 6723.pdf, 7765.pdf

I would like to move to each folder and move the .pdf's so that they are all in one folder like "allpdf" with a script

I had tried this:

for folder in *; do
  cd $folder
  mv "*.pdf" "../"
done

Solution

  • Minimal and Simple Solution:

    If you're using bash shell, then try this: You should be in the parent directory of all the subdirectories with pdf files in it. So, let's call your parent directory as pdf_parent_dir and this directory should contain in it the folders 4553, 6723, 7765 etc with pdf files in them, then run the commands as below:

    # moving to the desired parent directory    
    cd pdf_parent_directory
    
    # to move files to this directory    
    mkdir allpdf 
    
    # to enable bash star globbing    
    shopt -s globstar 
    
    # finally moving all pdf files from subdirectories to allpdf directory    
    mv **/*.pdf allpdf/
    

    Based on what you mentioned there shouldn't be any files with same name, but if there are, then the mv command will fail as it tries to move files with same name into the final allpdf/ directory

    I tried this on my Linux machine by creating a similar folder and file structure as you mentioned and it worked as expected. If you face any errors, let me know