Unix shell脚本:找到“文本模式”时注入文本(Unix shell script: Inject text when “text pattern” is found)

编程入门 行业动态 更新时间:2024-10-25 16:23:13
Unix shell脚本:找到“文本模式”时注入文本(Unix shell script: Inject text when “text pattern” is found)

假设我有两个文件: - data.txt - report.txt

该报告包含一些带有“占位符”的文本,例如:

HPLC results for sample: <insert-sample-id-here>, elements analyzed: <insert-element-name>

数据文件包含一系列“键/值”行:

sampleID: 123456abc elementName: genericThickeningAgent

这里不是计算机专家,但我知道“查找和替换”的任务可以由计算机自动化; 应该使用什么样的命令“在用我的数据文件中的匹配对的值替换占位符后重写report.txt”?

Say I have two files: - data.txt - report.txt

The report contains a text with some "placeholders", example:

HPLC results for sample: <insert-sample-id-here>, elements analyzed: <insert-element-name>

The data file contains a series of "key/value" lines:

sampleID: 123456abc elementName: genericThickeningAgent

Not a computer whiz here, but I know the task of "find and replace" can be automated by the computer; What sort of command should be used to "rewrite report.txt after replacing the placeholders with the value of the matching pairs from my data file"?

最满意答案

在文件的当前形式中,很难将数据文件中的值与报表文件中的占位符匹配,因为占位符<insert-sample-id-here>与data.txt中的sampleID不同。 <insert-element-name>不等于elementName 。

但假设您有不同形式的data.txt :

insert-sample-id-here: 123456abc insert-element-name: genericThickeningAgent

(因此,如果data.txt中的键与report.txt占位符匹配),则可以使用以下命令:

$ perl -ne 'print "s/<$1>/$2/g\n" if /^(.*?):\s+(.*)$/' data.txt | \ xargs -I% perl -p -i -w -e "%" report.txt

这将替换report.txt所有占位符:

$ cat report.txt results for sample: 123456abc, elements analyzed: genericThickeningAgent

In the current form of the file, it would be hard to match values from data file to placeholders in report file, because placeholder <insert-sample-id-here> is different than sampleID from data.txt. The same for <insert-element-name> being not equal to elementName.

But assuming you have data.txt in a different form:

insert-sample-id-here: 123456abc insert-element-name: genericThickeningAgent

(so if keys in data.txt are matching placeholders in report.txt) you can use this command:

$ perl -ne 'print "s/<$1>/$2/g\n" if /^(.*?):\s+(.*)$/' data.txt | \ xargs -I% perl -p -i -w -e "%" report.txt

Which will replace all the placeholders in report.txt:

$ cat report.txt results for sample: 123456abc, elements analyzed: genericThickeningAgent

更多推荐

本文发布于:2023-07-05 07:53:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034882.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   脚本   模式   shell   Unix

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!