Search code examples
bashcatxargsmv

How to move list of files from different directories to new directory using bash


I used find ./busd/ -type f -iname '*.pdf' | less to look for .pdf files on my second drive and there are hundreds of results from different subdirectories but I only needed to copy/move selection of pdf files to new directory.

I copy pasted their paths/filenames to moveme.txt.

I am thinking of cat moveme.txt | xargs command but i am stocked there. Please help.

I tried cat moveme.txt | xargs -0 -I % sh -c 'sudo mv -v % /new/directory/' and failed. How to do this right?

edit: I like to add that this path/filenames have spaces. Maybe it matters.

excerpt from moveme.txt:

./busd/0128/csm/sorting/read-ables/linus/CLI/Bash-Beginners-Guide-new.pdf
./busd/0128/csm/3t2/readables/etc/xulin/Shell Scripting.pdf
./busd/0128/csm/dais6/Dearables/assorted/Bash Pocket Reference - Arnold Robbins.pdf

Solution

  • Suggesting to dry-run printing each ireversible mv cmd before execution:

      awk '{cmd = "mv \"" $0 "\" /new/directory/"; print cmd}' moveme.txt
    

    When ready to execute mv command:

      awk '{cmd = "mv \"" $0 "\" /new/directory/"; system(cmd)}' moveme.txt
    

    Another option is to transform your moveme.txt file into a bash script using sed command and inspect moveme.sh before execution.

      sed -r 's|(^$)|mv "\1" /new/directory/|' moveme.txt > moveme.sh
    

    Inspect moveme.sh and run it.

      chmod a+x ./moveme.sh
      bash ./moveme.sh