[英]Shell script Sed - How to read a file and write in another file only in the first occurrence of a string?
I am trying to read the content of the file test.txt and write in another file Report.html, only in the first match of a string. 我正在尝试读取文件test.txt的内容,并仅在字符串的第一个匹配项中写入另一个文件Report.html。 Something like: 就像是:
sed -i '/, past/r test.txt' Report.html
This command above is reading all strings ", past" and including the content of the test.txt in all strings ", past". 上面的命令读取所有字符串“过去”,并在所有字符串“过去”中包含test.txt的内容。 But I just want that includes in the first occurrence of the string ", past". 但我只想在字符串“,过去”的首次出现中包含该字符串。 A command like: 像这样的命令:
sed -i '0,/, past/r test.txt' Report.html
The command above is not working, what's the correct syntax for that? 上面的命令不起作用,正确的语法是什么?
As the sed r
command does not take range, and sed control does not otherwise allow "first only", I think you need to "calculate" the line number of interest and feed that to sed: 由于sed r
命令的范围不大,并且sed控件不允许“仅第一”,因此我认为您需要“计算”感兴趣的行号并输入要sed的行:
sed -i $(awk '/, past/{print NR;exit}' Report.html)'r test.txt' Report.html
Only do this if you're guaranteed that , past
occurs in Report.html somewhere. 只有做到这一点,如果你保证 , past
在Report.html发生的地方。 If not, store the $(awk...)
result in a variable and check it first. 如果不是,请将$(awk...)
结果存储在变量中,然后首先检查它。 Otherwise the sed
will do the include for every line. 否则, sed
将对每一行进行包含。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.