Awk-1-liner for summing numbers in stdin, when printing the number of occurrences of a certain text along with other textured text

I'm definitely interested in getting a book about awk. I was defeated, despite playing with him for a short time. However, at the same time, I have a problem that I suspect that I can only solve with [g] awk. To demonstrate, I will use some fdisk output. In this example, the desired end result will look something like this:

Disks: 2 [240 GB total]
sda=120 GB
sdb=120 GB

Here is what I have:

fdisk -l 2>/dev/null | awk '/^Disk \/dev\/[vsh]d./ {bytes+=$5} END {print "Disks: "NR" ["; gb=bytes/1024/1024/1024; print gb" GB total]"}'

My NR seems to print 73. on my laptop with two hard drives. I don’t get it. Bye, okay .. I may be halfway. Any advice or short tutorials will be greatly appreciated!


After two basic excellent answers, I got the following:

echo DISKS: $(fdisk -l 2>/dev/null | awk -F/ '/^Disk \/dev\/[vsh]d.|^Disk \/dev\/xvd./{print$3}' | awk '{d++;bytes+=$4;disk[$1]=$2" "$3}END{gb=bytes/1024/1024/1024; printf gb" GB total, "d" disks\n";for (i in disk) print "  "i,disk[i]}' | sed -e "s/,$/ /" -e "s/: / /")

:

DISKS: 78.3585 GB total, 2 disks
  sda 80.0 GB
  sdb 4110 MB

, awk sed.:) , , !

+3
2
$ fdisk -l 2>/dev/null | awk '/^Disk \/dev\/[vsh]d./{d++;bytes+=$5;disk[$2]=$3$4} END {printf "Disks: "d" ["; gb=bytes/1024/1024/1024; printf gb" GB total]\n";for (i in disk) print i,disk[i]}'
Disks: 1 [93.1604 GB total]
/dev/sda: 100.0GB,
+2

, . , NR - (), , . .

fdisk -l 2>/dev/null | awk '/^Disk \/dev\/[vsh]d./ {bytes+=$5; disks+=1} END {print "Disks: "disks" ["; gb=bytes/1024/1024/1024; print gb" GB total]"}'

:

Disks: x [
yyy GB total]

, :

fdisk -l 2>/dev/null | awk '/^Disk \/dev\/[vsh]d./ {cur_bytes=$5; bytes+=cur_bytes; disks+=1; gsub(/dev|:|\//, "", $2); print $2 "=" cur_bytes/1024/1024/1024 " GB";} END {printf "Disks: "disks" ["; gb=bytes/1024/1024/1024; print gb" GB total]"}'

:

sda=xx GB
sdb=yy GB
sdc=zz GB
Disks: 3 [ww GB total]

. .

+1

Source: https://habr.com/ru/post/1757240/


All Articles