Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ls or dir - limit the number of file name returns

Tags:

ls

cygwin

dir

Is there a way to limit the number of filenames to be returned using the ls or dir command? I'm on a windows machine with cygwin, so either command will do.

I have a directory with over 1 million docs that I need to batch out into subfolders. I'm looking to write a simple script that would list the first 20,000 or so, move them to a subfolder, then repeat on the next 20,000. I would expect ls or dir to have an option to list only a certain number of files, but I can't seem to find a way to do it.

My other option is to print the filenames out to a text file and parse that to make the moves. It seems like there should be a simpler solution though.

like image 339
Dan Avatar asked Jan 19 '23 09:01

Dan


1 Answers

If you are using cygwin, you should be able to use the head command, like this:

ls | head -20000

to list the first 20 thousand.

If you want to move the batch in 1 command line, something like this should work:

ls | head -20000 | xargs -I {} mv {} subdir

(where subdir is the subdir you want to move the files to).

Run this first (with the echo command) to verify it will work before running the actual move:

ls | head -20000 | xargs -I {} echo mv {} subdir

Just be careful though, since you are moving files into a subdir, because the "ls" command will probably pick up your subdirs as well.

If they are all txt files, you could do something like this:

ls | grep txt$ | head -20000 | xargs -I {} mv {} subdir

to get files that end in txt

like image 69
BrianH Avatar answered Jan 31 '23 13:01

BrianH