tags:

views:

1389

answers:

4

How do I truncate output in BASH?

For example, if I "du file.name" how do I just get the numeric value and nothing more?

later addition:
all solutions work perfectly. I chose to accept the most enlightning "cut" answer because I prefer the simplest approach in bash files others are supposed to be able to read.

+6  A: 
du | cut -f 1
Tomalak
beat me to it by 20 seconds :)
Ken
Beat me by 30 seconds :) I've deleted my duplicate answer and added an alternative answer instead.
Mark Baker
I'd prefer more information about delimiters and ranges since he was only using du as an example. Then I'll happily delete too :)
Ken
Can I just copy yours or do I have to invent my own? :-)
Tomalak
Please just copy if you think they are ok - if not invent your own
Ken
I've no idea what the etiquette is here - if you want to add the detail to yours I can presumably still just delete?
Ken
Don't bother. My answer was faster, yours was more complete. So yours has been rightfully accepted, that's how this site works. I've got my share of up-votes. :-D
Tomalak
+7  A: 

If you know what the delimiters are then cut is your friend

du | cut -f1

Cut defaults to tab delimiters so in this case you are selecting the first field.

You can change delimiters: cut -d ' ' would use a space as a delimiter. (from Tomalak)

You can also select individual character positions or ranges:

ls | cut -c1-2
Ken
You can add something like "cut -d ' ' -f 1-2", to point out how to change the characters cut uses as delimiters.
Tomalak
+9  A: 

I'd recommend cut, as others have said. But another alternative that is sometimes useful because it allows any whitespace as separators, is to use awk:

du file.name | awk '{print $1}'
Mark Baker
+1 If the delimiter could be any whitespace, then awk is the most robust solution (even if it's not as pretty as using cut).
Jeremy Cantrell
A: 

If you just want the number of bytes of a single file, use the -s operator.

SIZE=-s file.name

That gives you a different number than du, but I'm not sure how exactly you're using this.

This has the advantage of not having to run du, and having bash get the size of the file directly.

It's hard to answer questions like this in a vacuum, because we don't know how you're going to use the data. Knowing that might suggest an entirely different answer.

Andy Lester
In the original question he said that using du was just an example; your answer doesn't help with his question (although it may in fact be useful to him if his example wasn't just hypothetical)
Mark Baker
I don't read it as "du was just an example".
Andy Lester
How do I truncate output in BASH?For example, if I "du file.name"...
Ken
Yes, I read that. And I didn't interpret it as "du was just an example."
Andy Lester
I don't understand how this is used. What's the context?
Dennis Williamson
Dennis Williamson