-2

How to find size of contents of directory in unix;

Without using du /awk ?

You can use ls -l | < set of commands only >

1

3 Answers 3

0

You could use the answer featured in [https://unix.stackexchange.com/a/238256/10525]

Which is

sudo ls -1d */ | sudo xargs -I{} du {} -sh && sudo du -sh

This isn't really doing what you want, but as you haven't stated why you don't want to use the correct tool for the job, I don't see how you're going to get a suitable answer.

2
  • As I mentioned; Strictly no use of du or awk. Aug 7, 2016 at 7:29
  • I don't think it's possible then. You could get the size of all files within the dir, but that's not what you've asked for. Aug 7, 2016 at 16:22
0

Since the requirement is not to use awk, we can use Perl one-liners.

ls -l | perl -lane 'print $F[4]'

where:

−l enables automatic line ending processing.
−a turns on automatic splitting of each input record into fields, stored
   in @F array.
−n includes an implicit input-reading loop. lines are not printed.
−e may be used to enter a single line of script. multiple −e commands
   build up a multiline script.`

Or if output of ls -l is of the following format(where the date includes month name):

-rw-r--r-- 1 root    root      0 Jul  1 06:25 alternatives.log
-rw-r--r-- 1 root    root    280 Jul  1 03:26 alternatives.log.1
-rw-r--r-- 1 root    root    179 Jun  9 03:15 alternatives.log.2.gz
-rw-r--r-- 1 root    root    294 Jan 12  2016 alternatives.log.3.gz
-rw-r--r-- 1 root    root    259 Oct  8  2015 alternatives.log.4.gz
-rw-r--r-- 1 root    root   2970 Sep  3  2015 alternatives.log.5.gz
-rw-r--r-- 1 root    root   2288 Aug 27  2015 alternatives.log.6.gz

we can use:

ls -l | grep -Po '(\d+) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)' | cut -d" " -f1

where in grep:

-P interprets the pattern as a Perl regular expression (PCRE) 
-o prints only the matched string
0

You're probably looking for the stat command. stat -f '%z' filename shows the size of the file.

You can combine this with recursive decent into the directory structure to get all the file sizes. Here's an example using find:

find . -type f -exec stat -f ' + %z' {} \; | xargs expr 0

The first part runs stat -f ' + %z' on each file in the directory (and all subdirectories). Consider you this structure:

$ ls -l
total 32
-rw-r--r--  1 eric  staff  2 Aug 21 18:13 a
-rw-r--r--  1 eric  staff  4 Aug 21 18:13 b
-rw-r--r--  1 eric  staff  6 Aug 21 18:13 c
-rw-r--r--  1 eric  staff  8 Aug 21 18:13 d

The find example above has this output:

$ find . -type f -exec stat -f ' + %z' {} \;              
 + 2
 + 4
 + 6
 + 8

xargs expr 0 says to take those lines and form the following command:

expr 0 + 2 + 4 + 6 + 8

Which yields the total of 20 bytes. Because you used find instead of just stat -f ' + %z' *, it will work files in subdirectories as well.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .