如何使用 bash 在两个已知行块之间的文件中插入一行(如果之前尚未插入)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8971314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert a line in a file between two blocks of known lines (if not already inserted previously), using bash?
提问by Luca Borrione
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)
我写了一个bash脚本,可以根据我的需要修改php.ini。
现在我不得不引入一个新的变化,我找不到明确的解决方案。
我需要修改 php.ini 才能插入(如果之前没有插入)
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
回答by Sjoerd
Get the line number using grep -n:
使用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 或 awk 插入它。在第 45 行插入“换行符”的示例:
sed '45i\newline' file
awk 'NR==45{print "newline"}1'
回答by potong
This might work for you:
这可能对你有用:
sed '/^; Dynamic Extensions ;$/,/^; Module Settings ;$/{H;//{x;/extension="memcache.so"/{p;d};/;;;\n/{s//&extension="memcache.so"\n/p}};d}' file
This will insert extension="memcache.so"between ; Dynamic Extensions ;and ; Module Settings ;unless extension="memcache.so"is already present.
这将插入extension="memcache.so"之间; Dynamic Extensions ;并; Module Settings ;除非extension="memcache.so"已经存在。
回答by jcollado
You can use the following sed script:
您可以使用以下 sed 脚本:
/^;\+$/{
N
/^;\+\n; Module Settings ;$/i extension="memcache.so"
}
Basically it matches these lines:
基本上它匹配这些行:
;;;;;;;;;;;;;;;;;;;
; Module Settings ;
and inserts before them the desired string (extension="memcache.so")
并在它们之前插入所需的字符串 ( extension="memcache.so")

