I am trying to use Mac Terminal command to move files to a new location.

I have a list of almost 2000 filenames with full paths in a text file. (All of them are in one parent directory, but distributed within multiple sub-directories.) I want to move these files into a single folder outside the parent directory.

How do I do this? I need the command to do something like this:

mv 'files listed in abc.txt' to destination

Thanks in advance.

  • How did you get to the textfile? There may be easy solutions. Otherwise looping the file line by line would be my choice, but there may be better. – Bernhard Nov 27 '12 at 18:48
  • I used grep -lir 'keyword' /parentdirectory/* > abc.txt to get the text file. – Spartanblogger Nov 27 '12 at 19:11

You could do something like create a tar file using your text file as an include file, then untar the file in the new location.

Or a one liner like this might work

while read -r i; do mv "$i" "/new/path/$i" ; done < abc.txt
  • Unfortunately, the filenames in abc.txt follow the format /parentfolder/subfolder_x/filename.xml, where x ranges from 1 to 36. I am trying to move them from these many different locations into a single destination folder. With the above command, I get an error "No such file or directory." It appears that the command is trying to recreate the entire directory structure (/subfolder_x.filename.xml) in the destination folder. Is there a way I can ignore the source path in each filename while moving to the destination folder? – Spartanblogger Nov 27 '12 at 21:37
  • @Spartanblogger did you change "/new/path" to path you want the files to go to? – jordanm Nov 27 '12 at 22:00
  • @jordanm Yes, I did. – Spartanblogger Nov 27 '12 at 22:07
  • It worked. Instead of "/new/path/$i" I used just "/new/path/" and it worked like a charm. Thank you! – Spartanblogger Nov 27 '12 at 22:38

Here is an example that doesn't require creating a temporary file first, and will work on all possible filenames:

for f in /parentdirectory/*; do
    if grep -q 'keyword' "$f"; then
        mv "$f" /someotherdir
  • How do I run this? In the terminal? Or in the AppleScript editor? – Spartanblogger Nov 27 '12 at 21:46
  • In a terminal. This code will work in any (mostly) POSIX-compliant shell (bash, dash, zsh, ksh, ...). – jordanm Nov 27 '12 at 21:58
  • Tried it. It did not do anything. – Spartanblogger Nov 27 '12 at 22:02

I tested this in debian for a list in which there was one file path per line

  cat list.txt | xargs mv -R -t copy_to_this_directory
  • 1
    I assume the files also didn't contain spaces. The mv on my Debian workstation from GNU coreutils doesn't have a -R option, and -t is a GNU extension that may not be available on Mac OS X – jordanm Nov 27 '12 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.