Bash: How to trim whitespace before using cut Bash: How to trim whitespace before using cut bash bash

Bash: How to trim whitespace before using cut


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.


tr helps here.

$ echo "Memory Limit:           12345 KB" | tr -s " " | cut -d " " -f312345
  • tr -s " " - squeeze all spaces into one
  • cut -d " " -f3 - split into columns by space and select third


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

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