我有一个通过shell脚本修改的文本文件。
我需要做以下事情:
例如,我的文件包含以下文字:
(some text)
(some text)
(text1_to_search)
(some text)
(text2_to_search) <- **This needs to be replaced only**
(text2_to_search)
(some text)
我只需要替换该特定行,并保持文件内容的其余部分不受影响。
答案 0 :(得分:2)
这是一种方式
awk '/text1_to_search/,/text2_to_search/ && !found{
if($0 ~ /text1_to_search/){found=0};
if($0 ~ /text2_to_search/){print "replacement";found=1;next}};
{print}'
对于两个不重叠的搜索/替换
awk '/text1_to_search/,/text2_to_search/ && !found{if($0 ~ /text1_to_search/){found=0};if($0 ~ /text2_to_search/){print "replacement";found=1;next}};
/Search_String2/,/Search_String3/ && !found2{if($0 ~ /SearchString2/){found2=0};if($0 ~ /Search_String3/){print "replacement2";found2=1;next}};
{print}'
答案 1 :(得分:0)
awk 'done{print;next}found&&/text2/{while(getline<"replacement")print;done=1;next}/text1/{found=1}1'
假设您有一个名为“replacement”的文件替换。 以下两个通过正则表达式替换:
sed '/text1/,/text2/s/text2/foo/' test.in
如果他们在同一条线上,这将取代那一个和下一个。以下内容仅会改变后者。
awk 'found&&!done&&/text2/{done=sub(/text2/,"foo")}/text1/{found=1}1' test.in