0

Does anyone actually know how to move X files at a time from one directory to another? Every 'example' on this page displays an error and is useless. I can only move fifty (50) files at a time, then 'sleep' for a period of time. The file names are all different but the extension is the same. As I've stated, every 'ls' example produces an error within Redhat.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
  • What’s the error that you get when moving more than 50 files? – Jeff Schaller Sep 11 '18 at 19:41
  • 5
    "Produces an error" is much less helpful than actually sharing with us what the error actually is, as it will usually (if sometimes abstrusely) explain what the precise problem is. Please edit your question to show the commands you are trying to execute, as well as the errors they yield. – DopeGhoti Sep 11 '18 at 19:53
  • By "Linux Redhat", do you mean Red Hat Enterprise Linux? – mattdm Sep 11 '18 at 22:54

2 Answers2

1

To move a given number of files at a time and sleeping 5 seconds in between moves you can use something similar to the following one-liner while in the source directory:

 while true; do mv -v $(ls -1 *yyy | head -n 5) otherdir/ ; sleep 5; done

Where yyy equals your common file extension, -n 5 represents moving 5 files at a time, and otherdir is your target directory. You will need to adjust the loop to suit your requirements, as listed here it will throw errors once all of the source files have been moved.

Jeff
  • 920
1

A small script, that could be adjusted to accept the extension and the destination directory, will accomplish this task:

#!/bin/bash

files=$(find . -maxdepth 1 -type f -name "*.txt" | head -n50)

while [[ ! -z $files ]]; do
  for f in $files; do
    mv $f ../t2
  done

  files=$(find . -maxdepth 1 -type f -name "*.txt" | head -n50)
done

Tested against a directory where I created 1,067 files, and them moved them.

I'm sure there is a way to optimize this script as well.

Edit:

As noted by a comment, the above script does not account for spaces. An approach that accounts for spaces (but not, perhaps, every special character, especially, perhaps carriage returns in the file names), might look like:

#!/bin/bash

function move50() {
  local NUM=0
  find . -name "*.txt" | head -n50 | (while read -r f; do
     echo "   $f"
      mv "$f" ../t2
      (( NUM++ ))
  done
  return $NUM)
}


cntr=1
while [[ $cntr -gt 0 ]]; do
  move50
  cntr=$?
done

This approach will handle files with spaces in the names.

KevinO
  • 845
  • Did you have a file named touch "foo bar.txt"? – Jeff Schaller Sep 11 '18 at 21:52
  • @JeffSchaller. made an edit that should account for spaces in file names. Thanks for noting the potential issue, even though I firmly believe spaces in filenames are evil... And it will work specifically with touch "foo bar".txt as a filename ;) – KevinO Sep 11 '18 at 22:39