Move a list of files(in a text file) to a directory?

I have a list of files, with their full paths, one per line in a file "files.txt"

I was trying to move all of those files from their original location to a new directory.

I CDed into the directory where they live now and issued

for file in ~/Desktop/files.txt do mv $file ~/newfolder

but nothing happens. I am sure I am missing something obvious


Solution 1:

bash won't read the contents of the file unless you tell it to.

for file in $(cat ~/Desktop/files.txt); do mv "$file" ~/newfolder; done

Solution 2:

You need to tell your loop to read the file, otherwise it is just executing:

mv ~/Desktop/files.txt ~/newfolder

In addition, as nerdwaller said, you need separators. Try this:

while read file; do mv "$file" ~/newfolder; done < ~/Desktop/files.txt

If your paths or file names contain spaces or other strange characters, you may need to do this:

while IFS= read -r file; do mv "$file" ~/newfolder; done < ~/Desktop/files.txt

Notice the quotes " around the $file variable.

Solution 3:

If the filenames do not contain whitespace:

mv -t dest_dir $(< text.file)

is probably the most concise way.

If there is whitespace in the filenames

while IFS= read -r filename; do mv "$filename" dest_dir; done < test.file

is safe.

Solution 4:

Try this:

python -c "import shutil; [shutil.move(_.strip(), 'new') for _ in open('files.txt').readlines()];"