Reputation: 1389
Using the command du
, I would like to get the total size of a directory
Output of command du myfolder
:
5454 kkkkk
666 aaaaa
3456788 total
I'm able to extract the last line, but not to remmove the string total
:
du -c myfolder | grep total | cut -d ' ' -f 1
Results in:
3456788 total
Desired result
3456788
I would like to have all the command in one line.
Upvotes: 0
Views: 100
Reputation: 289495
Why don't you use -s
to summarize it? This way you don't have to grep "total"
, etc.
$ du .
24 ./aa/bb
...
# many lines
...
2332 .
$ du -hs .
2.3M .
Then, to get just the value, pipe to awk
. This way you don't have to worry about the delimiter being a space or a tab:
du -s myfolder | awk '{print $1}'
From man du
:
-h, --human-readable
print sizes in human readable format (e.g., 1K 234M 2G)
-s, --summarize
display only a total for each argument
Upvotes: 1
Reputation: 74596
I would suggest using awk for this:
value=$(du -c myfolder | awk '/total/{print $1}')
This simply extracts the first field of the line that matches the pattern "total".
If it is always the last line that you're interested in, an alternative would be to use this:
value=$(du -c myfolder | awk 'END{print $1}')
The values of the fields in the last line are accessible in the END
block, so you can get the first field of the last line this way.
Upvotes: 0
Reputation: 16556
That's probably because it's tab delimited (which is the default delimiter of cut):
~$ du -c foo | grep total | cut -f1
4
~$ du -c foo | grep total | cut -d' ' -f1
4
to insert a tab, use Ctrl+v, then TAB
Alternatively, you could use awk to print the first field of the line ending with total
:
~$ du -c foo | awk '/total$/{print $1}'
4
Upvotes: 1
Reputation: 27822
First of, you probably want to use tail -n1
instead of grep total
... Consider what happens if you have a directory named local
? :-)
Now, let's look at the output of du
with hexdump
:
$ du -c tmp | tail -n1 | hexdump -C
00000000 31 34 30 33 34 34 4b 09 74 6f 74 61 6c 0a |140344K.total.|
That''s the character 0x09
after the K
, man ascii
tells us:
011 9 09 HT '\t' (horizontal tab) 111 73 49 I
It's a tab, not a space :-)
The tab character is already the default delimiter (this is specified in the POSIX spec, so you can safely rely on it), so you don't need -d
at all.
So, putting that together, we end up with:
$ du -c tmp | tail -n1 | cut -f1
140344K
Upvotes: 1