I want to replace the following line:
我想替换以下行:
--memory 20g \
with
同
--memory 100g \
Actually it should replace any number after --memory
. Following is what I have, but not able to get the expected result.
实际上它应该在--memory之后替换任何数字。以下是我所拥有的,但无法获得预期的结果。
sed -i -E -- "s/\b--memory.*/--memroy 100g \/g" a.txt
1 个解决方案
#1
6
You don't need the extended regex support here (-E
), POSIX-ly you could just do as below. The idea is you need to double-escape the meta-character \
to make it a literal
你不需要这里的扩展正则表达式支持(-E),POSIX-ly你可以这样做。这个想法是你需要双重转义元字符\才能使它成为文字
sed 's/--memory \(.*\) \\/--memory 100g \\/g' a.txt
or if you are sure its going to be 20g
all the time, use the string directly.
或者如果你确定它一直是20克,直接使用字符串。
sed 's/--memory 20g \\/--memory 100g \\/g' a.txt
The one advantage of using \(.*\)
is that allows you to replace anything that could occur in that place. The .*
is a greedy expression to match anything and in POSIX sed
(Basic Regular Expressions) you need to escape the captured group as \(.*\)
whereas if you do the same with the -E
flag enabled (on GNU/FreeBSD sed
) you could just do (.*)
. Also use regex anchors ^
, $
if you want to match the exact line and not to let sed
substitute text in places that you don't need. The same operation with ERE
使用\(。* \)的一个优点是允许您替换在该位置可能发生的任何事情。 。*是一个贪婪的表达式来匹配任何东西,在POSIX sed(基本正则表达式)中你需要将捕获的组转义为\(。* \),而如果你在启用-E标志时也这样做(在GNU / FreeBSD上) sed)你可以做(。*)。如果你想匹配确切的行而不是让sed在你不需要的地方替换文本,也可以使用正则表达式锚点^,$。与ERE相同的操作
sed -E 's/--memory (.*) \\/--memory 100g \\/g' file
#1
6
You don't need the extended regex support here (-E
), POSIX-ly you could just do as below. The idea is you need to double-escape the meta-character \
to make it a literal
你不需要这里的扩展正则表达式支持(-E),POSIX-ly你可以这样做。这个想法是你需要双重转义元字符\才能使它成为文字
sed 's/--memory \(.*\) \\/--memory 100g \\/g' a.txt
or if you are sure its going to be 20g
all the time, use the string directly.
或者如果你确定它一直是20克,直接使用字符串。
sed 's/--memory 20g \\/--memory 100g \\/g' a.txt
The one advantage of using \(.*\)
is that allows you to replace anything that could occur in that place. The .*
is a greedy expression to match anything and in POSIX sed
(Basic Regular Expressions) you need to escape the captured group as \(.*\)
whereas if you do the same with the -E
flag enabled (on GNU/FreeBSD sed
) you could just do (.*)
. Also use regex anchors ^
, $
if you want to match the exact line and not to let sed
substitute text in places that you don't need. The same operation with ERE
使用\(。* \)的一个优点是允许您替换在该位置可能发生的任何事情。 。*是一个贪婪的表达式来匹配任何东西,在POSIX sed(基本正则表达式)中你需要将捕获的组转义为\(。* \),而如果你在启用-E标志时也这样做(在GNU / FreeBSD上) sed)你可以做(。*)。如果你想匹配确切的行而不是让sed在你不需要的地方替换文本,也可以使用正则表达式锚点^,$。与ERE相同的操作
sed -E 's/--memory (.*) \\/--memory 100g \\/g' file