我试图从 lshw 获取结果并将它们添加到 bash 数组中,以便我可以创建一个新字符串。我在用
lshw -class disk |egrep -A 7 .'-d' |grep 'product' |cut -b 17-
输出看起来像这样
Samsung SSD 850
Samsung SSD 840
ST8000AS0002-1NA
ST8000AS0002-1NA
Samsung SSD 870
Samsung SSD 870
ST8000VN0022-2EL
Flash Drive FIT
Flash Drive FIT
ST8000AS0002-1NA
ST8000VN0022-2EL
Samsung SSD 870
Samsung SSD 870
ST8000VN004-2M21
我尝试将此输出添加到 bash 数组中,但每行以空格分隔的单词都成为数组中的一个元素。您还可以查看此命令的结果
for w in $(lshw -class disk |egrep -A 7 .'-d' |grep 'product' |cut -b 17-); do printf "$w \n" ;done
输出
Samsung
SSD
850
Samsung
SSD
840
ST8000AS0002-1NA
ST8000AS0002-1NA
Samsung
SSD
870
Samsung
SSD
870
ST8000VN0022-2EL
Flash
Drive
FIT
Flash
Drive
FIT
ST8000AS0002-1NA
ST8000VN0022-2EL
Samsung
SSD
870
Samsung
SSD
870
ST8000VN004-2M21
如何将空格分隔的行保留为一串?
答案1
mapfile
可能是最简单的。
mapfile -t myarray < <(lshw -class disk |egrep -A 7 .'-d' |grep 'product' |cut -b 17-)
但是,如果您不想使用文字数组而只想对结果进行循环,则可以这样做:
lshw -class disk |egrep -A 7 .'-d' |grep 'product' |cut -b 17- | while read w ; do [something with w] ; done
答案2
引用命令替换:
# for w in "$(lshw -class disk |egrep -A 7 .'-d' |grep 'product' |cut -b 17-)"; do printf "$w \n" ;done
USB3.0 DISK00
USB3.0 DISK01
USB3.0 DISK02
MS/MS-Pro
SD/MMC
Compact Flash
SM/xD-Picture
ST1000DM003-1CH1
WDC WD20EZAZ-00G
然后您会得到:“USB3.0 DISK00”“USB3.0 DISK01”...被传递到for
循环中。