Ls or dir - limit the number of file name returns

Is there a way to limit the number of returned file names using the ls or dir command? I am on a windows machine with cygwin, so any command will do.

I have a directory with more than 1 million documents that I need to release into subfolders. I want to write a simple script that will list the first 20,000 or so, move them to a subfolder, and then repeat the next 20,000. I would expect ls or dir to be able to list only a certain number of files, but I cannot find way to do it.

My other option is to print the file names in a text file and analyze what moves to do. There seems to be a simpler solution.

+4
source share
2 answers

If you are using cygwin, you should be able to use the head command, for example:

ls | head -20000 

to list the first 20 thousand.

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

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

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

Run this first (using the echo command) to make sure that it will work before the actual move starts:

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

Just be careful as you move files to subdir because the ls command will probably pick up your subdir as well.

If these are all txt files, you can do something like this:

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

to get files that end in txt

+7
source

Or you can combine head and tail to retrieve records from the middle:

Sample data:

 banana cherry apple orange plum strawberry redcurrant 

Now skip 2 entries and select the following 2:

 cat fruit.txt | head -n 4 | tail -n 2 

This will give you:

 apple orange 

So, head -n 4 will return the first 4 entries (banana to orange), and the next tail -n 2 will get the last 2 from this previous result (apple to orange), and not from the source file.

+2
source

All Articles