I would like to create linux script line that goes through each line of the output and adds up the 2nd column of numbers and also separately sums up the 4th column of numbers, to then print out both sums
$ df | grep "/mnt" | sort -n -k2 -r
/dev/sdb1 2883220084 90152 2853810896 1% /mnt/b
/dev/sda1 1952208720 290495232 1642161972 16% /mnt/a
/dev/sdc1 975584768 77856 965722916 1% /mnt/c
/dev/sdd1 975584748 77852 965722900 1% /mnt/d
/dev/sde2 107003844 24 101522180 1% /mnt/e
This line only does it for the largest line. I'd like for it to add all lines.
$ df | grep "/mnt" | sort -n -k2 -r | head -1 | awk '{print $2" "$4}'
How can I do that, please?
CodePudding user response:
No need for greping, sorting or head.
df | awk '/\/mnt/{a =$2;b =$4}END{printf "%s\t%s\n",a,b}'
awk
processes every line that matches /mnt
, adding the values of $2
in a
, and $4
in b
. Once processing is done (in the END
statement) we print them.
CodePudding user response:
Pure Bash:
#! /bin/bash
exec <<EOF
/dev/sdb1 2883220084 90152 2853810896 1% /mnt/b
/dev/sda1 1952208720 290495232 1642161972 16% /mnt/a
/dev/sdc1 975584768 77856 965722916 1% /mnt/c
/dev/sdd1 975584748 77852 965722900 1% /mnt/d
/dev/sde2 107003844 24 101522180 1% /mnt/e
EOF
sum2=0
sum4=0
while read c1 c2 c3 c4 rest; do
let sum2 =$c2 sum4 =$c4
done
printf '%s\n' "$sum2" "$sum4"