搜索文本文件的特定行,最多替换一个字符 [英] Search for specific line of text file, replace up to a certain character
问题描述
在文件my_file.ini
中,我想像这样修改以dataspecs
开头的行:
In file my_file.ini
, I want to modify the line starting with dataspecs
like so:
将dataspecs old_val old stuff blah blah ! blah blah
替换为
dataspecs $new_val ! blah blah
,其中new_val
是bash变量,并且保留!
之后的所有内容.另外,我不知道old_val
的值.
dataspecs $new_val ! blah blah
, where new_val
is a bash variable, and everything after the !
is preserved. Also, I don't know the value of old_val
.
我不在乎它是sed
还是awk
还是bash,我只是在寻找一个我能理解的简单答案.我真的很感激一个解决方案,特别是如果您可以为刚刚学习sed和awk的人(不是最容易看的代码)解释该解决方案的代码意味着什么.谢谢!
I don't care whether it's sed
or awk
or just bash, I'm just looking for a simple answer that I can understand. I would really appreciate a solution, especially if you could explain what the code of the solution means, for someone who is just learning sed and awk (not the easiest code to look at). Thanks!
推荐答案
使用sed:
sed -i.bak "s/^\( *dataspecs \)[^\!]*/\1${new_val} /" my_file.ini
PS:我正在使用sed的内联标志-i
进行内联编辑,这将保存修改后的文件.
PS: I am using inline flag -i
of sed for inline editing, this will save the modified file.
这篇关于搜索文本文件的特定行,最多替换一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!