使用sed/awk替换文本文件的一部分 [英] Replace section of text file using sed/awk
本文介绍了使用sed/awk替换文本文件的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试如下替换#begin和#end之间的文件中的文本:
I'm trying to replace the text in a file between # begin and # end as follows:
# begin
# [block]
# param1=""
# param2=""
# end
读取为:
# begin
[block]
param1="value1"
param2="value2"
# end
基本上,我不会注释[block]行以及它下面的参数值.
Basically, I'm uncommenting the [block] line as well as the param values that fall under it.
推荐答案
使用Mac OS X的BSD sed 1 :
A simpler solution that avoids unneeded loops, using Mac OS X's BSD sed1:
/# begin/,/# end/ { # Search only within this range of text.
//!s/^# // # Excluding range borders, delete /^# / from each line.
}
测试:
▶ cat > FILE <<EOF
aaa
bbb
# begin
# [block]
# param1=""
# param2=""
# end
ccc
ddd
EOF
▶ sed -i '' '/# begin/,/# end/{//!s/^# //;}' FILE
▶ cat FILE
aaa
bbb
# begin
[block]
param1=""
param2=""
# end
ccc
ddd
进一步的解释:
- 请注意,空正则表达式
//
会重复最后一个正则表达式匹配项.因此,//!
将其否定.并且/PAT1/,/PAT2/{ //! X }
具有将X
和/PAT2/
都排除在X
之外的效果.
- Note that the empty regular expression
//
repeats the last regular expression match. Thus,//!
negates that. And/PAT1/,/PAT2/{ //! X }
has the effect of excluding both/PAT1/
and/PAT2/
forX
.
1 并使用GNU sed进行了测试.
1 And also tested using GNU sed.
这篇关于使用sed/awk替换文本文件的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文