Reputation: 609
I have a file with many occurences of a string. For instance:
Bergson
BErgson Bergso
\a{Henri Bergson}
Henri BERgson bergson
I want to encapsulate the word Bergson
(with unsensitive case) in \a{...}
but only if the word is not already inside the command \a{...}
.
So the result must be
\a{Bergson}
\a{BErgson} Bergso
\a{Henri Bergson}
Henri \a{BERgson} \a{bergson}
I am trying using sed
but it was too complicated for me or maybe it is not the right tool.
Do you have any idea how I can do this?
Upvotes: 2
Views: 204
Reputation: 1093
sed -r '
s/(\\a\{[^}]*ber)(gson[^}]*\})/\1#\2/Ig;
s/bergson/\\a{&}/gI;
s/(ber)#(gson)/\1\2/gI' input.txt
Explanation:
s/(\\a\{[^}]*ber)(gson[^}]*\})/\1#\2/Ig;
- replaces strings, which shouldn't be touched to the \a{Henri Berg#son}
(inserts hash sign into the "Bergson" word).
[^}]*
and [^}]*
are needed for non-greedy matching. s/bergson/\\a{&}/gI;
- substitutes all needed "bergsons" by the standard way.
s/(ber)#(gson)/\1\2/gI
- removes #
from the Berg#son
, reverting it back to the original form.
Input (complicated for testing)
Bergson
BErgson Bergso
\a{Henri Bergson} bergson \a{Bergson} another words
Henri BERgson bergson
Output
\a{Bergson}
\a{BErgson} Bergso
\a{Henri Bergson} \a{bergson} \a{Bergson} another words
Henri \a{BERgson} \a{bergson}
Upvotes: 1
Reputation: 6335
With gnu sed:
$ sed '/\\a{.*bergson.*}/I! s/bergson/\\a{&}/gI'
\a{Bergson}
\a{BErgson} Bergso
\a{Henri Bergson}
Henri \a{BERgson} \a{bergson}
Alternative:
sed '/\\a{.*bergson.*}/In; s/bergson/\\a{&}/gI' file1
Upvotes: 1