Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace line with space and backslash with a string containing spaces

Tags:

linux

unix

sed

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.

sed -i -E -- "s/\b--memory.*/--memroy 100g \/g"  a.txt
like image 720
blackfury Avatar asked May 28 '18 05:05

blackfury


1 Answers

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

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

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
like image 166
Inian Avatar answered Nov 18 '22 19:11

Inian