[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Including ' in a sed command



On 2025-08-07 at 22:17, Tim Woodall wrote:

> iHi All,
> 
> (Typed, rather than cut/pasted so apologies if there's a typo)
> 
> This is part of a sed command in a bash script.
> 
> sed 's/["'"'"']//'
> 
> This matches " or '. It works.
> 
> But it's 'unreadable' and almost impossible to find the typo if it's
>  wrong.
> 
> Is there a better way of writing it? the obvious '["\']' doesn't
> work.

That depends on your threshold for "better".

The problem, of course, is the overlap in characters between those
needed for the s-expression and those parsed by the shell.

My best stab at it, which is only arguably better, looks like:

sed 's/["'\'']//'

That's:


' opens a string-literal block, so the shell doesn't eat characters by
treating them as shell syntax

s opens the s-expression

/ tells the s-expression what its delimiter will be

[ opens an alternation block in the regex

" is the first character to be matched in the alternation block

' closes the open string-literal block

\ tells the shell to treat the next character as literal

' is that literal character, and becomes the second character to be
matched in the alternation block

' opens another string-literal block

] closes the alternation block in the regex

/ is the s-expression delimiter

/ is the s-expression delimiter

' closes the open string-literal block


It only saves one character over the version you gave, and it's not
necessarily a *whole* lot more readable - but IMO it's *somewhat* more
so, if only from having fewer consecutive / interleaved quotation
characters.


Alternatively you could probably do

sed s/\[\"\'\]//

, i.e. forgo string quotation entirely and rely entirely on backslashes
to escape the sensitive characters - but I don't know if that's any more
readable overall, and it's probably more trouble to type.

(I'd guess Greg Wooledge will probably present a better solution, and
possibly take me to task for a sloppy one. But oh well.)

-- 
   The Wanderer

The reasonable man adapts himself to the world; the unreasonable one
persists in trying to adapt the world to himself. Therefore all
progress depends on the unreasonable man.         -- George Bernard Shaw

Attachment: signature.asc
Description: OpenPGP digital signature


Reply to: