所以我有一个输出以逗号分隔的字符串的命令
喜欢这个;
"Name","Type","FC Ports","iSCSI Ports","User Group","Cluster","Performance Class"
"mnlas-esxq01","default","100000051EC20A95,100000051EC20A96,100000051EC21AC3,100000051EC21AC4","","","MNLASDMZ CL-1","none"
"mnlas-esxa02","default","100000051EC20D3A,100000051EC20D3B,100000051EC2218D,100000051EC2218E","","","MNLASDMZ CL-1","none"
"mnlas-esx916","default","21000024FF4DDC20,21000024FF4DDC21,21000024FF490CFC,21000024FF490CFD","","","MNLASPRODSCCM CL-1","none"
"mnlas-esx417","default","21000024FF4DDBE8,21000024FF4DDBE9,21000024FF490F56,21000024FF490F57","","","MNLASPRODSCCM CL-1","none"
"mnlas-esx111","default","21000024FF4DDC56,21000024FF4DDC57,21000024FF490F00,21000024FF490F01","","","MNLASPRODSCCM CL-1","none"
"mnlas-p-xca09.pr.int.ptc.com","default","21000024FF514CF4,21000024FF514CF5","","","MNLAS P-xca CL-1","none"
"mnlas-p-xca10.pr.int.ptc.com","default","21000024FF514ED2,21000024FF514ED3","","","MNLAS P-xca CL-1","none"
"mnlas-p-xca11.pr.int.ptc.com","default","21000024FF514FB6,21000024FF514FB7","","","MNLAS P-xca CL-1","none"
"mnlas-esx403.ad.cibc.com","default","10008C7CFF702490,10008C7CFF702491,10008C7CFF702494,10008C7CFF702495,10008C7CFF652604,10008C7CFF652605,10008C7CFF20D0A8,10008C7CFF20D0A9","","","MNLASPRODSQL CL-1","none"
"mnlas-esx401.ad.cibc.com","default","10008C7CFF702484,10008C7CFF702485,10008C7CFF7023F4,10008C7CFF7023F5,10008C7CFF21B3E8,10008C7CFF21B3E9,10008C7CFF65203E,10008C7CFF65203F","","","MNLASPRODSQL CL-1","none"
如您所见,长度也不同。
我的目标是回显名称,iSCSI端口和群集,但有时某些字段也为空。
如何正确格式化它并使用grep查找看起来像这样的主机名。
Name iSCSI Ports Cluster
mnlas-esxq01 100000051EC20A95,100000051EC20A96 MNLASDMZ CL-1
顺便说一句,由于端口数量的缘故,iSCSI端口往往会更长一些,因此CLuster字段应进行调整
我尝试使用此命令,但是没有用。它说
sh-4.2# cat temp/testS | grep -i esx401 | while read "Name" "Type" "iSCSI Ports" "User Group" "Cluster" "Performance Class";do echo $Name $"iSCSI Ports" $Cluster;done
sh: read: `iSCSI Ports': not a valid identifier
我也尝试将其定义为变量,但是没有用。
任何帮助将不胜感激。
答案 0 :(得分:1)
这是“名称”的定义,外壳程序将其用于变量和函数名称:
name
由仅由字母,数字和下划线组成的单词,并以字母或下划线开头。名称用作外壳程序变量和函数名称。也称为标识符。
不允许在变量名中使用空格。
鉴于此,使用CSV文件有时会非常棘手。非常棘手,您应该使用正确的CSV解析器。 csvkit是一套很好的工具:
csvcut -c "Name,iSCSI Ports,Cluster" file.csv
答案 1 :(得分:1)
当您不想使用csv解析器并且字段中没有双引号时,可以尝试下一种解决方法:
while IFS=$'\r' read -r name type fcports scsi user cluster remainer; do
printf "%-40s %-20s %-20s\n" "${name}" "${scsi}" "${cluster}"
# or use ${fcports} to show output like your example
done < <(sed 's/","/\r/g' file.csv | tr -d '"')