BASH: how to substitute a expression with another without creating a new file
Hi guys,
I'm writting a script in BASH and I want to find the expression "int foo[i] = true;" in a text and substitute it by the word "boo[i]= true;", but without erasing other words from the text and without having to create a new file. Would somebody know how I can do that? Text for example: whi(&M§)/&§M)POM;M;(29073()/§()"/§;();§/()"7§ZE/§)&§=)"&/=)$&=!&$=! waxe83qmi3u,jy,einure,xl9me23uy9, int foo[i] = true;i23904802y97p,94280 u2908/M="(§?;$(/EZ"Zolsdwiea,ru8 q2xi4l9i<ey93 2x5093405 int foo[i]= true; 39i2e09ui9,y92ßi049. |
sed -i -e 's/int\ foo\[i\]=true\;/something\ else/g' myfile
TBH, the escape characters mightn't be exactly correct, but it's the -i option for sed you're really looking for. |
Hi Cris!
That works perfectly. Thanks a lot ;) Actually would you also know how can I tell 'sed' to substitute just the first match? |
well the "g" makes sed do multiple replacements in the same line, so if you remove that it'll only do it once per line.
|
Why execute sed as an external process when bash can just do it inline?
Code:
#! /bin/bash Quote:
|
Code:
$ more file |
Quote:
Code:
1) int foo[i]= true |
Quote:
Code:
match=$'int[ \t]+foo\[i\][ \t]*=[ \t]*true[ \t]*;' Code:
[[ "$line" =~ "$match" ]] && line="int boo[i] = true; If you really want to go ape Code:
match=$'int([ \t]+)foo\[i\]([ \t]*=[ \t]*)true([ \t]*);' |
Hi guys,
first thanks for all replies ;) I think I didn't express myself the right way. What I wanted to ask with "would you also know how can I tell 'sed' to substitute just the first match?" was that I want to know if it's possible to use 'sed' to erase or substitute just the first occurency of the searched pattern in the file, so if I have: text text PATTERN text PATTERN text PATTERN text So, is there a way of substituting the first occurency of PATTERN in the file and erasing the other ones? So that at the end I have: text text SUBSTITUTED PATTERN text text text |
All times are GMT -5. The time now is 12:34 AM. |