Bash技术实现:将SysName字段值插入文本第一列的方案问询
需求:提取SysName值并插入每行开头
需要将testinv文件每行中SysName="*"的取值提取出来,插入到该行的第一列。
现有库存文件 testinv 内容
Device_Classification="Systems" device_role="web server" SysName="Server1" MachineType="Windows 2019 Server" Environment="PROD" Application_name="Solarwinds" Device_Classification="Systems" device_role="App Server" SysName="Server2" MachineType="RHEL 8" Environment="PROD" Application_name="Solarwinds" Device_Classification="Systems" device_role="App Server" SysName="Server3" MachineType="RHEL 7" Environment="PROD" Application_name="Solarwinds"
期望输出
Server1 Device_Classification="Systems" device_role="web server" SysName="Server1" MachineType="Windows 2019 Server" Environment="PROD" Application_name="Solarwinds" Server2 Device_Classification="Systems" device_role="App Server" SysName="Server2" MachineType="RHEL 8" Environment="PROD" Application_name="Solarwinds" Server3 Device_Classification="Systems" device_role="App Server" SysName="Server3" MachineType="RHEL 7" Environment="PROD" Application_name="Solarwinds"
现有脚本 bashscript_INV.sh 内容
#!/bin/bash sed '/results/d; /\[/d ; /\]/d; /{/d ; /}/d' toprocess_asINV | xargs -n 12 | sed 's/:/=/g; s/= /="/g; s/,/"/g; s/$/"/g' | grep -oh SysName=".*" | awk {'print $1'} | sed 's/SysName="//g; s/"//g' | tee testinv
实现方案
直接处理现有testinv文件
使用awk可以一次性完成匹配和插入操作:
awk '{match($0, /SysName="([^"]+)"/, arr); print arr[1], $0}' testinv
- 原理:通过
match函数匹配行中的SysName="..."格式,将引号内的内容捕获到数组arr中,随后先输出捕获的SysName值,再输出整行内容。
修改现有脚本生成目标文件
原脚本仅提取了SysName值,可调整管道逻辑,直接生成带SysName前缀的行:
#!/bin/bash sed '/results/d; /\[/d ; /\]/d; /{/d ; /}/d' toprocess_asINV | xargs -n 12 | sed 's/:/=/g; s/= /="/g; s/,/"/g; s/$/"/g' | awk '{match($0, /SysName="([^&]+)"/, arr); print arr[1], $0}' | tee testinv
- 调整说明:移除原脚本中用于单独提取SysName的
grep和后续sed步骤,改用awk直接在处理后的每行中匹配带"转义的SysName值,插入到行首后保存到testinv。
内容的提问来源于stack exchange,提问作者George Obed
相关产品推荐
相关产品推荐

