Reputation: 3761
Take the example:
$ du -h file_size.txt
112K file_size.txt
How would I remove the filename from the output of du -h
?
I have tried to use sed
to search for a string (the filename) and replace it with nothing, but it hasn't worked - command below:
du -h file_size.txt | sed 's/ 'file_size.txt'//'
Could someone please point out why this won't work, or perhaps a better way to do it?
Upvotes: 17
Views: 10857
Reputation: 2915
why not just stat
it ?
stat -f '%z' vg1.mp4 # BSD-stat
821258414
gstat -c '%s' vg1.mp4 # GNU-stat
821258414
if u insist on the du
way, getting first column is cleaner than mentioned :
du -smh vg1.mp4 | awk NF=1
783M
or the wc
way - using <
redirection sends the file over the pipe, so u don't need to trim out the filename —- somehow BSD-wc pads in an extra space
gwc -c < vg1.mp4 # GNU-wc
821258414
wc -c < vg1.mp4 # BSD-wc
821258414
Upvotes: 1
Reputation: 316
To deal with filenames containing newlines:
$ du -h $'./filename\nwith\nnewlines.txt' | awk 'NR==1 { print $1 }'
4.0K
There's a really cool sed
solution, using a "print and quit" trick, pulled from here:
$ du -h $'./filename\nwith\nnewlines.txt' | sed -E -n '/(.*)\t.*/{s//\1/p;q;}'
4.0K
Most of the other answers on here can't deal with newlines (except for ghostdog's set
answer):
$ du -h $'./filename\nwith\nnewlines.txt' | cut -f1
4.0K
with
newlines.txt
Upvotes: 0
Reputation: 342969
the output of du -h
is [tab] delimited.
du -h file_size.txt |sed 's/[\t].*//g'
Upvotes: 0
Reputation: 5036
Your original command would have worked except that you are including a space in the sed regexp, and du outputs tabs.
Upvotes: 0
Reputation: 342969
@OP if your data has distinct fields, for example spaces/tabs, then its easier to use tools like awk/cut to split them on those fields by delimiters. Using regex (eg sed ) is not necessary. Even better is just using the shell.
various ways
$ du -h file | awk '{print $1}'
4.0K
$ du -h file | cut -f1
4.0K
$ set -- $(du -h file) #using shell only
$ echo $1
4.0K
Upvotes: 0
Reputation: 5243
This is a little more verbose, but in any case, this is another way to what you want:
du -h file_size.txt |while read x junk; do echo $x; done
Upvotes: 0
Reputation: 94799
Simple output the first column. Here is the awk solution
du -h test.txt | awk '{ print $1 }'
Upvotes: 5
Reputation: 225162
You have some bad quoting in that command line. The simplest is probably:
du -h file_size.txt | cut -f -1
To fix your command line:
du -h file_size.txt | sed 's/file_size.txt//'
Since your post has an awk
tag:
du -h file_size.txt | awk '{ print $1 }'
Upvotes: 22