如何插入已知的线两个块之间的文件的行(如果尚未插入previously),使用bash? [英] How to insert a line in a file between two blocks of known lines (if not already inserted previously), using bash?

查看:121
本文介绍了如何插入已知的线两个块之间的文件的行(如果尚未插入previously),使用bash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个bash脚本,可以根据我的需要修改php.ini中。结果
现在我就来介绍一个新的变化,我无法找到一个明确的解决方案吧。结果
结果
我需要修改php.ini文件以便插入(如果尚未插入previously)结果

 扩展=memcache.so

结果
块之间

  ;;;;;;;;;;;;;;;;;;;;;;
;动态扩展;
;;;;;;;;;;;;;;;;;;;;;;

和块

  ;;;;;;;;;;;;;;;;;;;
;模块设置;
;;;;;;;;;;;;;;;;;;;

可能之前的第二个。结果
任何人都可以帮助我吗?在此先感谢

编辑:通过解决

 如果! grep的-Fxq'延长=memcache.so''php.ini中';然后
    线= $(猫php.ini中'| grep的-n';模块设置;| grep的-o'^ [0-9] *')
    线= $((线 - 2))
    须藤SED -i $ {}行'I \\延长=memcache.so''php.ini中'
科幻


解决方案

获取使用的grep -n 的行号:

 行= $(猫php.ini文件| grep的-n模块设置| grep的-o'^ [0-9] *')

计算行插入文本:

 行= $((线 -  3))

使用awk或者sed插入。例如插入换行上线45:

  sed的'45I \\换行'文件
awk的'NR == 45 {打印换行} 1'

I wrote a bash script which can modify php.ini according to my needs.
Now I have to introduce a new change, and I cannot find a clear solution to it.

I need to modify php.ini in order to insert (if not already inserted previously)

extension="memcache.so" 


between the block

;;;;;;;;;;;;;;;;;;;;;;
; Dynamic Extensions ;
;;;;;;;;;;;;;;;;;;;;;;

and the block

;;;;;;;;;;;;;;;;;;;
; Module Settings ;
;;;;;;;;;;;;;;;;;;;

possibly just before the second one.
Can anyone help me please? Thanks in advance

EDITED: solved by using

if ! grep -Fxq 'extension="memcache.so"' 'php.ini'; then
    line=$(cat 'php.ini' | grep -n '; Module Settings ;' | grep -o '^[0-9]*')
    line=$((line - 2))
    sudo sed -i ${line}'i\extension="memcache.so"' 'php.ini'
fi

解决方案

Get the line number using grep -n:

line=$(cat php.ini | grep -n 'Module Settings' | grep -o '^[0-9]*')

Calculate the line to insert the text to:

line=$((line - 3))

Insert it using sed or awk. Examples to insert "newline" on line 45:

sed '45i\newline' file
awk 'NR==45{print "newline"}1'

这篇关于如何插入已知的线两个块之间的文件的行(如果尚未插入previously),使用bash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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