sed – 当它不存在时添加一行

我有一个文件formsweb.cfg这可能看起来有点像这样

 # These match variables (eg %form%) in the baseHTML file. Their values # may be overridden by specifying them in the URL query string # (eg "http://myhost.example.com/forms/frmservlet?form=myform&width=700") # or by overriding them in a specific, named configuration (see below) [default] # Default Oracle Forms values: #baseHTML=base.htm #baseHTMLjpi=basejpi.htm width=1366 height=734 [sepwin] separateFrame=True lookandfeel=Generic [debug] serverURL=/forms/lservlet/debug 

这个文件缺less键值clientDPI=96 ,它应该位于这个文件的[default]部分。

在100多个网站上,某些文件可能设置了clientDPI,其他文件可能不会。

我想将这个值添加到当前没有的文件中。

这是我写的sed脚本。 有没有“更好”的方法来做到这一点?

 sed -n '/\[default\]/,/^\[/ { /^clientDPI/q1 }' formsweb.cfg && sed '/\[default\]/,/^\[/ { /^\[default\]/ { a\ clientDPI=96 } }' -i.bak.${RANDOM} formsweb.cfg 

它检查clientDPI是否存在于[默认]和下一个[字符之间。 如果是这样,则退出1 ,否则,转到下一个执行插入操作的sed行。

GNU sed版本4.1.5

你可以使用sed脚本来完成这个任务,或者使用分支来只执行一次sed,但是当你问一个更好的方法时,我会使用一个更通用的脚本,更容易适应。 毕竟,明天你可能会想将“lookandfeel”改为“newgeneric”,或者将“serverURL”改为“/ forms / lservlet / debugmore”。 例如:

  • Crudini
  • perl模块Config :: IniFiles
  • 推出自己的