1

I'm trying to remove strings surrounded by other strings (\[ and \]) in sed. I can match the start string \[ easily, but after that I wan't to match any characters including \ and ] but not if they are in a row (\] end string).

Is that possible ?

  • please add sample input and output for testing and clarity... – Sundeep Nov 24 '16 at 3:17
  • @Sundeep, here's what I'm trying to do with this : s=echo $PS1 | sed .... Then by removing every unprintable characters (contained between \[ and \]). I am able to count the length of $PS1. I'm doing this with something that will be part of $PS1, not $PS1 itself. – kbenoit Nov 24 '16 at 17:52
2

sed -e 's/\\\[\([^\\]\|\\[^]]\)*\\\]//g'

Anatomy of the search pattern:

\\\[             starting delimiter
    \(
      [^\\]      not a backslash
           \|    or
      \\[^]]     a backslash followed by any char except a right bracket
    \)*          repeat as many times as possible
\\\]             ending delimiter
  • Well thanks, that seams to work! But there is an error when run inside subshell ? Weird ? (inside backticks or $(...)). Simple example: x= `echo stuff | sed -e 's/\\\[\([^\\]\|\\[^]]\)*\\\]//g' ` – kbenoit Nov 24 '16 at 16:24
  • 1
    Backticks are weird. They eat backslashes. The preferred syntax is $(...). Use x="$(echo stuff | sed -e 's/\\\[\([^\\]\|\\[^]]\)*\\\]//g')". – AlexP Nov 24 '16 at 16:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.