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

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

问题描述

我写了一个bash脚本,可以根据我的需要修改php.ini.
现在我不得不引入一个新的变化,我找不到明确的解决方案.

我需要修改 php.ini 才能插入(如果之前没有插入)

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" 


块之间

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

和块

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

可能就在第二个之前.
有人可以帮我吗?提前致谢

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

通过使用解决

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}'iextension="memcache.so"' 'php.ini'
fi

推荐答案

使用 grep -n 获取行号:

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

计算要插入文本的行:

line=$((line - 3))

使用 sed 或 awk 插入它.在第 45 行插入换行符"的示例:

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

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

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

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