Petar Yakov
Petar Yakov

Reputation: 179

Bash get size of a list of files extracted with head command

I have have the following bash command, which gives me 300 random files of a folder.

ls /directory/ | sort -R | head -n 300

I want to get the total size of the 300 random file like so

ls /directory/ | sort -R | head -n 300 | du -h

The problem is that 'du' is not executed for these 300 files but for the whole directory where I currently am.

How can I do it?

Upvotes: 1

Views: 50

Answers (1)

Timur Shtatland
Timur Shtatland

Reputation: 12377

Use find and xargs like so:

find /directory -mindepth 1 -maxdepth 1 | sort -R | head -n300 | xargs du -sh

To print also the total size of all the files that xargs fed to du, add the -c option to du, like so: du -sch

Upvotes: 1

Related Questions