[英]insert a specific line after occurrence with Unix
I need insert a new line with specific content after find a pattern in text1 file with shell. 在带壳的text1文件中找到模式后,我需要插入一行包含特定内容的新行。
I have a file text_file_1.txt
with this content: 我有一个文件text_file_1.txt
其中包含以下内容:
aaaaaa
bbbbbb
patternrefrefref
cccccc
aaaaaa
patternasdasd
pattern
zzzzzz
and a text_file_2.txt
with this content: 以及具有以下内容的text_file_2.txt
:
111111
333333
555555
and I need insert the first line of text_file_2.txt
(that is, 111111
) when I find the first occurrence of "pattern" of text_file_1.txt
and 333333
when I find the second occurrence of "pattern (always pattern)... 当我找到text_file_1.txt
的“ pattern”的第一个匹配项时,我需要插入text_file_2.txt
的第一行(即111111
),而当我发现第二个“ pattern(总是模式)”时,则需要插入333333
...
Final result will be: 最终结果将是:
aaaaaa
bbbbbb
pattern_refrefref
111111
cccccc
aaaaaa
pattern_asdasd
3333333
pattern
555555
zzzzzz
I found how to insert a new line with a new text after a pattern but always insert the same text, I don't need that. 我发现了如何在模式后插入带有新文本的新行,但是总是插入相同的文本,我不需要。
This is easily done using awk: 使用awk可以很容易地做到这一点:
awk 'FNR==NR{a[FNR]=$0; next} 1; /pattern/{print a[++i]}' text_file_2.txt text_file_1.txt
aaaaaa
bbbbbb
patternrefrefref
111111
cccccc
aaaaaa
patternasdasd
333333
pattern
555555
zzzzzz
FNR==NR
we are reading all the lines from file2 and storing them in an indexed array a
. 在第一块FNR==NR
我们从file2中读取所有行并将它们存储在索引数组a
。 pattern
we print one line from array and increment the counter. 每当遇到pattern
时,在遍历file2时,我们从数组中打印一行并增加计数器。 i think you are looking for something like this... 我认为您正在寻找类似的东西...
sed '/what_you_want_to_find /a what_you_want_to_add' text_file_1.txt
if you also want to save the changes in the same file just use this: 如果您还想将更改保存在同一文件中,请使用以下命令:
sed -i '/what_you_want_to_find /a what_you_want_to_add' text_file_1.txt
to help you a bit more, at the point that you add what new you want to get printed, so in what_you_want_to_add
, you can do it like this. 为了进一步为您提供帮助,您可以添加要打印的新内容,因此在what_you_want_to_add
,您可以像这样进行操作。 Save each line every time in variable outside of the sed, for example you want to get line number 5. 每次将每行保存在sed之外的变量中,例如,您要获取第5行。
line= awk 'NR==5' text_file_2.txt
and you can use the variable each time to print the new line, so it would like this in your case. 并且您可以每次使用该变量来打印新行,因此您需要使用该变量。 sed '/what_you_want_to_find /a $line' text_file_1.txt sed'/ what_you_want_to_find / a $ line'text_file_1.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.