我想用 awk 从一个文件中提取特定的值:
输入文件:
EVS 58 (EVSTEST1):
Export name: /EXPORT1
Export path: /opt/export1
File system label: fs_test1
File system size: 18.7 GB File system free space: 16.5 GB
File system state:
formatted = Yes
mounted = Yes
failed = No
thin provisioned = No
Access snapshots: No
Display snapshots: No
Read Caching: Disabled Disaster recovery setting:
Recovered = No Transfer setting = Use file system default
Export configuration:
EVS 59 (EVSNEXT):
Export name: /next
Export path: /next
File system label: fs_next
File system size: 9.75 GB File system free space: 2.28 GB
File system state:
formatted = Yes
mounted = Yes
failed = No
thin provisioned = No
Access snapshots: No
Display snapshots: No
Read Caching: Disabled Disaster recovery setting:
Recovered = No Transfer setting = Use file system default
Export configuration:
10.26.xx.xx(rw,norootsquash)
10.26.xx.xx(rw,norootsquash)
10.26.xx.xx(rw,norootsquash)
我需要提取行: EVS 和 EVS ID、导出名称、导出路径、文件系统标签和导出配置(如果存在)。
得到如下输出:
58;EVSTEST1;/EXPORT1;/opt/export1;fs_test1;-
59;EVSNEXT;/next;/next;fs_next;10.26.xx.xx(rw,norootsquash);10.26.xx.xx(rw,norootsquash);10.26.xx.xx(rw,norootsquash)
但是,使用下面的脚本,我无法获取所有“导出配置”行。我只有第一个。我尝试了 for 循环,如果没有成功则尝试了几次。
#!/bin/bash
LST_NFS=$(cat lst_nfs.txt | awk -F= '\
($1~/^EVS/) { gsub(/\(/,"" );gsub(/\)/,"" ) ; gsub(/:/,"" ); split($0,parts," ") ;evsid=parts[2];evsname=parts[3] }
($1~/ Export name/) { split($0,parts," ") ; name=parts[3] }
($1~/ Export path/) { split($0,parts," ") ; path=parts[3] }
($1~/ File system label/) { split($0,parts," ") ; fs=parts[4] }
($1~/ Export configuration:/) { getline;
if ( $1~ /^[0-9]+/) { export1=$1; getline;
printf "%s;%s;%s;%s;%s;%s\n",evsid,evsname,name,path,fs,export1}
else { export1="-";
printf "%s;%s;%s;%s;%s;%s\n",evsid,evsname,name,path,fs,export1 }
}')
echo -e "$LST_NFS"
我的脚本结果:
57;EVSTEST1;/EXPORT1;/opt/export1;fs_test1;-
59;EVSNEXT;/next;/next;fs_next;10.26.xx.xx(rw,norootsquash)
非常感谢您的帮助。
问候,
格雷格
最佳答案
每当你在输入数据中使用 name = value 对时,最好创建一个 name2value 数组,然后只打印你喜欢的名称:
$ cat tst.awk
BEGIN { OFS=";" }
{ gsub(/^[[:space:]]+|[[:space:]]+$/,"") }
$1=="EVS" {
gsub(/[()]/,"")
n2v["EVS"] = $2
n2v["EVS ID"] = $3
}
inEC {
if (NF) {
n2v[name] = (name in n2v ? n2v[name] OFS : "") $0
}
else {
n2v[name] = (name in n2v ? n2v[name] : "-")
prtRec()
delete n2v
inEC = 0
}
}
/^Export configuration:/ { sub(/:.*/,""); name=$0; inEC=1 }
!inEC {
name = value = $0
sub(/[[:space:]]*:.*/,"",name)
sub(/[^:]+:[[:space:]]+/,"",value)
n2v[name] = value
}
END { prtRec() }
function prtRec() {
print n2v["EVS"], n2v["EVS ID"], n2v["Export name"], n2v["Export path"], \
n2v["File system label"], n2v["Export configuration"]
}
$ awk -f tst.awk file
58;EVSTEST1:;/EXPORT1;/opt/export1;fs_test1;-
59;EVSNEXT:;/next;/next;fs_next;10.26.xx.xx(rw,norootsquash);10.26.xx.xx(rw,norootsquash);10.26.xx.xx(rw,norootsquash)
关于bash - awk,从文件中提取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35801363/