I am trying to make the command to return the disk usage on the folders that occupy 1+ GiBs, but somehow the second variable in the command only prints out the value of first variable. Also, the values of the totals are printed not in the column, but as a generic text, using spaces as a separator. What am I doing wrong here?

OUTPUT="$(sudo ls -lah -R |awk '/^total/ {print $2}' |sort -h)"; GIGS="$(echo $OUTPUT | grep G | sed 's/G//')"; echo $GIGS

The newlines inside your command substitution variable OUTPUT get preserved until they are word-split when you echo them for the GIGS command substitution -- that's when your output turns into a single space-separated line. Quote the variable to preserve the newlines. The GIGS variable is almost a copy of your OUTPUT variable -- you should notice that the very first "G" in it has been deleted. You may be trying to delete all of the G's, in which case you'll want to use sed 's/G//g'.

End result:

OUTPUT="$(sudo ls -lah -R |awk '/^total/ {print $2}' |sort -h)"; GIGS="$(echo "$OUTPUT" | grep G | sed 's/G//g')"; echo $GIGS

or, broken to multiple lines:

OUTPUT="$(sudo ls -lah -R |awk '/^total/ {print $2}' |sort -h)";
GIGS="$(echo "$OUTPUT" | grep G | sed 's/G//g')"; 
echo $GIGS

As a possible simplification, consider doing more work in awk:

sudo ls -alhR | awk '/^total/ && /G$/ { print substr($2, 1, length($2)-1) }' | sort -n

This extends your awk matching pattern to require that the line end in a 'G' (taking care of your grep), then strips the trailing (G) character from the string before printing it; then it's a simple sort -n at the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.