微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试使用 awk 解析 lscpu 输出但无法正确执行

如何解决尝试使用 awk 解析 lscpu 输出但无法正确执行

本质上我想要的是从 lscpu提取 L3 缓存的字节大小。棘手的部分是 lscpu 使用的单位在不同版本之间不一致,我需要使用所有版本(包括 --bytes 选项可用之前的版本)。我所看到的 lscpu 将使用 K、KiB、M 或 MiB,这就是我要解析的内容

这是 lscpu 输出内容

Architecture:          x86_64
cpu op-mode(s):        32-bit,64-bit
Byte Order:            Little Endian
cpu(s):                16
On-line cpu(s) list:   0-15
Thread(s) per core:    1
Core(s) per socket:    1
Socket(s):             16
NUMA node(s):          1
vendor ID:             GenuineIntel
cpu family:            6
Model:                 60
Model name:            Intel Core Processor (Haswell,no TSX,IBRS)
Stepping:              1
cpu MHz:               2299.998
BogoMIPS:              4599.99
Virtualization:        VT-x
Hypervisor vendor:     KVM
Virtualization type:   full
L1d cache:             32K
L1i cache:             32K
L2 cache:              4096K
L3 cache:              16384K
NUMA node0 cpu(s):     0-15
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology eagerfpu pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm invpcid_single ssbd ibrs ibpb tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat md_clear spec_ctrl

这就是我目前所拥有的,但似乎无法完成。

$ lscpu | awk '/L3 cache:/{print $3$4;next};/(M|MiB)$/{printf "%u\n",$3*(1024*1024);next};/(K|KiB)$/{printf "%u\n",$3*1024;next}'
0
32768
32768
4194304
16384K

任何想法如何调整我的 awk 命令以使其正常工作?

编辑: 我的预期输出只是:

16777216

解决方法

Cyrus 的回答确实是最佳选择,但如果您使用 awk,请尝试以下操作:

 awk -F: 'BEGIN{def=1024}/^L3/{if($2~/M/){def=def*def}; printf "%u\n",$2*def}'
,

以字节为单位获取 3 级缓存 (L3):

getconf LEVEL3_CACHE_SIZE
,
$ cat tst.awk
BEGIN {
    mult["K"]   = 1000
    mult["KiB"] = 1024
    mult["M"]   = mult["K"]^2
    mult["MiB"] = mult["KiB"]^2
}
sub(/^L3 cache:/,"") {
    smbl = $NF
    sub(/[^[:alpha:]]+/,"",smbl)
    print $0 * mult[smbl]
}

$ awk -f tst.awk file
16384000

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。