0

I have a small question regarding for loops in linux bash scripts.

I have a folder that contains 10000 files. I wrote for loop to list 100 files from the 10000.

For a in ~/Desktop/folder/*.txt
Do

    Echo $a

Done

However, I need to list the biggest 100 files in the folder and not the first 100 files depending on alphabet.

2 Answers 2

2

Why are you using a for loop? If you just want to see the 100 biggest files, do:

ls -S | head -n 100
Sign up to request clarification or add additional context in comments.

1 Comment

Just as an addon - if you want the filesizes as well you can do ls -Ss | head -n 100
0

If you do the loop just to get the files, be aware that there is a tool for that: ls.

See the man page of ls for commands which suit your problem: man ls

To answer your question:

You can use the output of ls -S, which sorts the files by size to loop over:

ls -S *.txt | while read file; do 
    echo $file
done

To limit the amount of files, you can use head. The following example will give output you the first 100 lines from the output of ls.

ls *.txt | head -n 100

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.