Bash: how to trim spaces before using cut

I have an output line from a command like this:

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

I'm trying to pull 12345. The first step - colon separation - works great

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

Trying to split it is that difficult. How can I trim spaces so that cut -d ' ' -f1 returns β€œ12345” rather than a space?

+5
source share
6 answers

Connect the command to awk, print the third column, space and 4th column, like this

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

This leads to:

 12345 KB 

or

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

if you want a bare number.

+5
source

You can use awk and avoid using cut, sed or regex:

 <command> | awk '/Memory Limit/{print $(NF-1)}' 12345 
  • /Memory Limit/ will make this print only a line with the text Memory Limit
  • $(NF-1) will provide you the last-1 th input field.
+3
source

Do you need to use cut ? cut intended to highlight only one character delimiter. I don’t think that cutting can be as simple as you expected.

sed is simple:

 $ echo "Memory Limit: 12345 KB" | sed 's/.*:\s*//' 12345 KB 

explanation:

.*:\s* matches all letters to the last colon, then after that matches all empty characters and deletes them, replacing the empty string.


it turns out that you were expecting one number. then I would say just go ahead and match the numbers:

 $ echo "Memory Limit: 12345 KB" | grep -o -P '\d+' 12345 
+2
source

bash also has a regex that you can use.

 result=$(<command> | grep "Memory Limit") regex='Memory Limit:[[:space:]]+([[:digit:]]+)[[:space:]]KB' if [[ $result =~ $regex ]]; then result=${BASH_REMATCH[0]} else # deal with an unexpected result here fi 

The value of $regex can be adjusted as needed.

+1
source

tr helps here.

 $ echo "Memory Limit: 12345 KB" | tr -s " " | cut -d " " -f3 12345 
  • tr -s " " - compress all spaces into one
  • cut -d " " -f3 - split into columns by space and select the third
+1
source

awk is probably best suited for this task, but here is an unorthodox way

 $ grep -oP "(?<=Memory Limit:)\s+[0-9]+" file | xargs 

lookbehind to match label and output only match, use xargs to remove spaces

0
source

All Articles