Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to trim whitespace before using cut

Tags:

bash

trim

cut

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?

like image 834
user2824889 Avatar asked Aug 05 '16 15:08

user2824889


People also ask

How do you trim white space in bash?

Use sed 's/^ *//g', to remove the leading white spaces. There is another way to remove whitespaces using `sed` command. The following commands removed the spaces from the variable, $Var by using `sed` command and [[:space:]].

How do I remove extra spaces in bash?

You can enable shopt -s extglob and then just use NEWHEAD=${NEWHAED/+( )/ } to remove internal spaces.


1 Answers

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.

like image 88
John Goofy Avatar answered Sep 25 '22 02:09

John Goofy