本文介绍了用空格替换行,并用包含空格的字符串替换反斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要替换以下行:

--memory 20g \

使用

--memory 100g \

实际上,它应该替换--memory之后的任何数字.以下是我所拥有的,但无法获得预期的结果.

Actually it should replace any number after --memory. Following is what I have, but not able to get the expected result.

sed -i -E -- "s/\b--memory.*/--memroy 100g \/g"  a.txt

推荐答案

此处不需要扩展的正则表达式支持(-E),只能通过POSIX进行以下操作.这个想法是,您需要对元字符\进行两次转义以使它成为文字

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

sed 's/--memory \(.*\) \\/--memory 100g \\/g' a.txt

,或者如果您确定它始终都是20g,请直接使用字符串.

or if you are sure its going to be 20g all the time, use the string directly.

sed 's/--memory 20g \\/--memory 100g \\/g' a.txt

使用\(.*\)的一个优点是,您可以替换该位置可能发生的任何事情. .*是一个贪婪的表达式,可以匹配任何内容,并且在POSIX sed(基本正则表达式)中,您需要将捕获的组转义为\(.*\),而如果在启用-E标志的情况下执行相同的操作(在GNU/FreeBSD sed),您可以执行(.*).如果要匹配精确的行,并且不让sed在不需要的地方替换文本,也可以使用正则表达式锚点^$.与ERE相同的操作

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

sed -E 's/--memory (.*) \\/--memory 100g \\/g' file

这篇关于用空格替换行,并用包含空格的字符串替换反斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 11:01