Trimming whitespace off the beginning of a variable in bash

Sometimes a variable can be returned with a few empty (whitespace) characters in front of it.  This is not too much of an issue when running individual commands ending in a | wc -l to count the number of lines, but when you want to sandwich the variable in between two words in a more meaningful echo statement in a script, that “gap” between the words and the numbers looks untidy.  To remove the preceeding whitespace, append the following into the command used to build the variable (between the back ticks `   `).

     sed -e ‘s/^[ \t]*//’

e.g. to count the number of folders…

     FOLDERCOUNT=`ls -l $SOURCE | grep ^d | wc -l | sed -e ‘s/^[ \t]*//’`

     echo “The $FOLDERCOUNT source folders are…”

Will output this…

     The 4 source folders are…

instead of this…

     The            4 source folders are…

Did you like this?
Tip cyberfella with Cryptocurrency

Donate Bitcoin to cyberfella

Scan to Donate Bitcoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to cyberfella

Scan to Donate Bitcoin Cash to cyberfella
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to cyberfella

Scan to Donate Ethereum to cyberfella
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to cyberfella

Scan to Donate Litecoin to cyberfella
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to cyberfella

Scan to Donate Monero to cyberfella
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to cyberfella

Scan to Donate ZCash to cyberfella
Scan the QR code or copy the address below into your wallet to send some ZCash:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.