Bash: How to trim whitespace before using cut

user2824889 picture user2824889 · Aug 5, 2016 · Viewed 20k times · Source

I have a line of output from a command like this:

[]$ <command> | grep "Memory Limit"
Memory Limit:           12345 KB

I'm trying to pull out the 12345. The first step - separating by the colon - works fine

[]$ <command> | grep "Memory Limit" | cut -d ':' -f2
           12345 KB

Trying to separate this is what's tricky. How can I trim the whitespace so that cut -d ' ' -f1 returns "12345" rather than a blank?

Answer

John Goofy picture John Goofy · Aug 5, 2016

Pipe your command to awk, print the 3rd column, a space and the 4th column like this

<command> | awk '{print $3, $4}'

This results in:

12345 KB

or

<command> | awk '{print $3}'

if you want the naked number.