15

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 hasnt worked (command below)

du -h file_size.txt | sed 's/ 'file_size.txt'//'

Could someone please point out why this wont work, or perhaps a better way to do it?

Regards

Paul

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
paultop6
  • 3,691
  • 4
  • 29
  • 37

9 Answers9

20

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 }'
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
14
du -h file_size.txt | cut -f1
Tomalak
  • 332,285
  • 67
  • 532
  • 628
5

Simple output the first column. Here is the awk solution

du -h test.txt  | awk '{ print $1 }'
tux21b
  • 90,183
  • 16
  • 117
  • 101
0

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
vezult
  • 5,185
  • 25
  • 41
0

@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
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
0

Your original command would have worked except that you are including a space in the sed regexp, and du outputs tabs.

Peter Westlake
  • 4,894
  • 1
  • 26
  • 35
0

the output of du -h is [tab] delimited.

du -h file_size.txt |sed 's/[\t].*//g'
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
0

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
Aeronautix
  • 301
  • 2
  • 13
0

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
RARE Kpop Manifesto
  • 2,453
  • 3
  • 11