Reputation: 21
I need to replace some strings in the file but when the string is inside curly braces, i need to skip it. Something like
sed -i '/[^{].*foo.*[^}]/ s/foo/bar/g' test.f
test file test.f contains something like this:
bar foo {foobar}bar {foo}
This should search only for foo in the string which is not wrapped in the braces. So the result should be:
bar bar {foobar}bar {foo}
Everything in the braces should be ignored, i.e. if the string starts with "{" it should be ignored until the corresponding "}" in the line.
This doesn't have to be performed by sed. Thanks a lot.
Sample Input:
bar foo {foobar}bar {foo}
foo { foo { foo } foo } foo
foo { foo } foo { foo } foo
Expected Output:
bar bar {foobar}bar {foo}
bar { foo { foo } foo } bar
bar { foo } bar { foo } bar
Upvotes: 2
Views: 135
Reputation: 1517
Just for fun!
awk '{sub(/foo/,"bar")}{sub(/ foo$/," bar")}{sub(/} foo {/,"} bar {")}1' file
bar bar {foobar}bar {foo}
bar { foo { foo } foo } bar
bar { foo } bar { foo } bar
Upvotes: 0
Reputation: 203149
$ cat tst.awk
{
gsub(/foo/,RS)
numChars = length()
rec = ""
for (charNr=1; charNr<=numChars; charNr++) {
char = substr($0,charNr,1)
if ( char == "{" ) { depth++ }
if ( char == "}" ) { depth-- }
rec = rec ((char == RS) && (depth == 0) ? "bar" : char)
}
gsub(RS,"foo",rec)
print rec
}
$ awk -f tst.awk file
bar bar {foobar}bar {foo}
bar { foo { foo } foo } bar
bar { foo } bar { foo } bar
Upvotes: 3