ls or dir - limit the number of file name returns
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 comman开发者_StackOverflowd 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.
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
Or you might want to combine head
and tail
to fetch entries out of the middle:
Example data:
banana
cherry
apple
orange
plum
strawberry
redcurrant
Now let's skip 2 entries and fetch the following 2 ones:
cat fruit.txt | head -n 4 | tail -n 2
That will give you:
apple
orange
So head -n 4
will return the first 4 entries (banana to orange) and the following tail -n 2
will get the last 2 ones out of that previous result (apple to orange) and not out of the original file.
精彩评论