Skip to content

Bash: Want to move certain amount of files, that contains spaces to a different directory

So I’m quite new with bash and Stack Overflow in general, so forgive me if I may be missing something.

I’ve been trying to create a script that moves a certain amount of files (ex: 3 files), that may contain spaces (like "hello world.txt"), to another directory.

I’ve tried a few different ways to get the files with spaces, but have all proven a little difficult and finally narrowed it down to just using *.csv. For instance the code will look like (simplified):

for file in *.csv; #grab 3 files
     echo "$file";
     mv "$file" "$TDIR"

I only want to move a certain amount of files, like 3. $TDIR in this case is a target directory to move them to.

I’ve done it this way because I’m able to grab the whole filename "Hello World.txt" instead of grabbing "Hello" and "World.txt".

I’ve tried using different things like:

ls -p | grep -v / | head -3

but it gives me the above result where it creates 2 files (the spaces causing problems).

Sorry it’s kind of long but I’ve been struggling with this and would greatly appreciate any help.



The minimum necessary change is to use the loop you have, but simply break out early:

((count = 3))
for file in *.csv ; do
     echo "$file"
     mv "$file" "$TDIR"
     [[ ${count} -eq 0 ]] && break;

The only real potential downside of this solution is that it may fail if you have a truly stupendous number of files, so many that the shell globbing starts to struggle under the load. However, I find it’s often easier than trying to remember or research the ninety-two find parameters that will enable the same behaviour 🙂

User contributions licensed under: CC BY-SA
10 People found this is helpful