I'm using Bash and \\+ works with grep but not with sed.

For example if I do

echo "abbbbc"| sed -e s/ab\\+c/def/

I obtain this result : abbbbc

I tried with ' or with " around s/ab\\+c/def/, I obtain the same result.

but if I replace \\+ with *, I obtain : def

I have to change >Atab_TR4682|c0_g1_i1|m.14206 into Atab

If I do echo ">Atab_TR4682|c0_g1_i1|m.14206" | sed -e "s/>*\\([[:alpha:]]\\\*)_.\*/\1/g"

I obtain Atab_TR4682|c0_g1 probably because * could also be used for 0 iteration, but if I replace * by \\+ it doesn't work at all..

Does anyone have an explanation?

  • Use sed -r to use extended regular expressions perhaps? – DopeGhoti Mar 24 '17 at 17:34
  • unable to reproduce iow works fine here - what's your sed version ?; @DopeGhoti - with ERE he'll have to remove the \ before the + – don_crissti Mar 24 '17 at 17:35
  • Not without strong quotes he won't (: – DopeGhoti Mar 24 '17 at 17:36
  • Is your sed already aliased to sed -r (or sed -E) maybe? That would turn \+ into + and vice versa – steeldriver Mar 24 '17 at 17:46
  • 1

GNU sed accepts an escaped +, so if your sed is GNU-compatible, you can do:

$ echo "abbbbc" | sed 's/ab\+c/def'
$ echo "abbbbc" | sed "s/ab\+c/def"
$ echo "abbbbc" | sed s/ab\\+c/def

The POSIX-specified (more generally available) sed command only uses POSIX BREs (basic regular expressions) by default. If your sed is POSIX-compatible but not GNU-compatible and you want x+ to act as xx*, then you want the -E switch:

$ echo "abbbbc" | sed -E 's/ab+c/def/'

Some non-GNU implementations of sed include -r as a synonym for -E, for compatibility with older versions of GNU sed. The -E syntax is POSIX, and recent GNU sed accept both.

  • @don_crissti Edited – Fox Mar 24 '17 at 17:48
  • Yes but isn't that (sed s/ab\\+c/def) what the OP claims that it's not working as expected ? – don_crissti Mar 24 '17 at 17:50
  • @don_crissti Yes — my assumption is that their sed is non-GNU (mine certainly is) – Fox Mar 24 '17 at 17:51
  • Let's see if the OP bothers replying to the comments... Anyway, if their grep supports \+ that means it's a gnu setup hence gnu sed – don_crissti Mar 24 '17 at 17:55

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.