Reputation: 1
I am using OSX and I'm having a problem while trying to replace a string in a file using the sed command. The problem is that the substitute string contains a square bracket.
In particular I want to replace this string "message--------------" (- are blanks)
with this one "message------[ yea ]"
but if I type
sed "message /s//message \ [ yea ]" filein > fileout
I get this message: bad flag in substitute command: '['
I tried to put a \ before the [ but it didn't work. Can anyone help? Thanks!
Upvotes: 0
Views: 4099
Reputation: 25032
Try this:
sed 's/message /&[ yea ]/g' filein > fileout
The &
is the expression matched. No special treatment is needed for the brackets.
It wasn't really clear to me how the spaces were intended to be handled. The above just adds [ yea ]
to the end of the fixed-length sequence of spaces. Should it be preferred to replace the last spaces of an arbitrary-length sequence of spaces with [ yea ]
, a more complicated command is needed:
sed 's/\(message \{1,\}\) /\1[ yea ]/g' filein > fileout
The idea in this case is to match a pattern that has two parts. First is a group, bracketed by \( \)
, which looks for the message
followed by one or more spaces (\{1,\}
. This must be followed by exactly seven spaces. When matching text is found, it is replaced by the text of the group (the \1
, indicating the first group) followed by [ yea ]
. The strategy here can be adapted to other search-replace patterns, with, e.g., multiple groups or different text.
Upvotes: 1
Reputation: 36229
Without counting the blanks exactly:
echo "message foo" | sed "s/message /message [ yea ]/"
message [ yea ] foo
The substitute-command is 's/IN/OUT/', while 'm...' is unknown - no m-command known. Another key to success, is, to mask the single character [ immediately, without a blank in between, with a backslash. However - on the right side of a substitution-expression, a group does not make much sense, so you don't need to mask them.
Upvotes: 0