解析文本文件中带有前缀“产品名称:”的特定字符串
大家好,我有一个脚本创建的文本文件(特别是 dmidecode > dmidecode.txt
),我希望能够获取“产品名称:”的内容,因此在本例中“ HP t5740e 瘦客户端”,但对于其他机器类型会略有不同。我可以使用 sed 来计数到第 44 行,然后将其分割,直到得到我想要的,但我希望它比这更动态。
文本文件:
41 Handle 0x0001, DMI type 1, 27 bytes
42 System Information
43 Manufacturer: Hewlett-Packard
44 Product Name: HP t5740e Thin Client
45 Version:
46 Serial Number: CNW1160BZ7
47 UUID: A0B86400-6BBD-11E0-8325-92EEE331A344
48 Wake-up Type: Power Switch
49 SKU Number: XL424AA#ABA
50 Family: 103C_53302C
我的代码似乎不起作用:
sed -c -i "s/\($TARGET_KEY *Product Name :*\).*/\1$REPLACEMENT_VALUE/" dmidecode.txt
我感觉我的正则表达式很遥远(可能是因为我查看的最初示例玷污了我的“愿景”)
非常感谢任何帮助! 另外,有人知道我可以查看任何好的正则表达式参考吗?
更新: 好吧,我可以在这上面花更多的时间,找到一些更好的例子,并从我的研究中得出这一点:
grep -e "Product Name: HP" -e "Product Name: hp" dmidecode.txt | awk '{print}'
当我添加 '{print $NF}'
时,它只打印最后一个单词,是有没有办法修改 print 以包含搜索字符串之后的所有内容而不是整行本身?
另外,我应该从一开始就注意到这一点,但我需要将输出放入变量中。
Hey guys I've got a text file that a script creates (specifically dmidecode > dmidecode.txt
) and I want to be able to grab the contents of "Product Name:" so in this case "HP t5740e Thin Client" but it will be slightly different for other machine types. I could just use sed
to count to line 44 and then slice it up until I get what I want but I'd like for it to be more dynamic than that.
Text file:
41 Handle 0x0001, DMI type 1, 27 bytes
42 System Information
43 Manufacturer: Hewlett-Packard
44 Product Name: HP t5740e Thin Client
45 Version:
46 Serial Number: CNW1160BZ7
47 UUID: A0B86400-6BBD-11E0-8325-92EEE331A344
48 Wake-up Type: Power Switch
49 SKU Number: XL424AA#ABA
50 Family: 103C_53302C
Code I have that doesn't seem to work:
sed -c -i "s/\($TARGET_KEY *Product Name :*\).*/\1$REPLACEMENT_VALUE/" dmidecode.txt
I get the feeling my regular expressions is way off (probably because the initial examples I looked at tainted my "vision")
Any help is greatly appreciated!
Also, anyone know of any good regular expression references I can check out?
UPDATE:
Ok I was able to spend a little more time on this, found some better examples and got this out of my research:
grep -e "Product Name: HP" -e "Product Name: hp" dmidecode.txt | awk '{print}'
When I add '{print $NF}'
it prints just the last word, is there a way to modify print to include everything after the search string instead of the whole line itself?
Also, I should have noted this from the beginning, but I need the output to go into a variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你甚至不需要 sed 来
解释
grep "Product Name"
只给我包含“Product Name”的行cut -f2 -d ":"
分割这些行使用“:”作为分隔符并返回第二个字段you won't even need sed for that
explanation
grep "Product Name"
give me only the lines containing "Product Name"cut -f2 -d ":"
split those lines using ":" as delimiter and the return second field使用 sed:
如果要删除
:
之后的空格:With sed:
If you want to remove spaces after
:
: