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 ?

2
  • please add sample input and output for testing and clarity...
    – Sundeep
    Nov 24, 2016 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, 2016 at 17:52

1 Answer 1

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
2
  • 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, 2016 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, 2016 at 16:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .