简体   繁体   English

Shell脚本Sed-仅在首次出现字符串时,如何读取文件并在另一个文件中写入?

[英]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.

相关问题 使用sed仅替换文件中字符串的第一个匹配项 - Replace only the First occurrence of a string in a file using sed sed仅修改文件中的第一列,如果匹配则不修改第一次出现 - sed to modify only first column in a file but not the first occurrence if it matches 替换文件中第一次出现的 sed 命令不起作用 - sed command to replace first occurrence in file is not working 如何在Shell脚本中使用sed命令进行替换,以将一个目录中存在的txt文件中的字符串替换为另一个目录中的字符串? - How to replace using sed command in shell scripting to replace a string from a txt file present in one directory by another? Shell脚本 - 列出文件,读取文件并将数据写入新文件 - Shell Script - list files, read files and write data to new file 我如何才能只匹配首次出现的字符? - How can I get sed to only match to the first occurrence of a character? 替换文本文件中首次出现的通配符字符串 - Replacing first occurrence of a wildcard string in text file sed:仅用该行中第一个出现的字符串替换单词,直到最后一次匹配 - Sed : replace words only with first occurrence of string in the line not till last match 用sed替换第一个匹配项 - Replace the first occurrence with sed 如何在一个字符的第一次出现和另一个字符的第一次出现之间提取字符串? - How to extract string between the first occurrence of a character and first occurrence of another character?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM