如何使用sed替换文件中第n次出现的字符串 [英] How to replace the nth occurrence of a sttring in a file using sed
本文介绍了如何使用sed替换文件中第n次出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法用sed替换文件中第n次出现的字符串?
Is there any way to replace the nth occurrence of a string in a file using sed?
如何更改它以替换第 n 次出现?
How can i change it so that it replaces the nth occurrence?
我的文件包含以下几行:
My file contents the following lines:
first line
second line
third line
jack
fifth line
jack
seventh line
考虑一个变量var = jill
.
我想用变量 $var
的值替换第二次出现的 jack.
I want to replace the 2nd occurrence of jack with value of variable $var
.
推荐答案
这可能对你有用(GNU sed):
This might work for you (GNU sed):
sed ':a;$!{N;ba};s/jack/'"$var"'/2' file
这会将文件拖入内存,然后将第二次出现的 jack
替换为 $var
.
This slurps the file into memory and then substitutes the second occurence of jack
for $var
.
这篇关于如何使用sed替换文件中第n次出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文