搜索文本文件的特定行,最多替换一个字符 [英] Search for specific line of text file, replace up to a certain character

查看:53
本文介绍了搜索文本文件的特定行,最多替换一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在文件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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆