-1

Say I want to match either sh or /sh. I've tried to change the order of the two characters like this [/^]sh$, but this will match /sh or ^sh, "the caret character" rather than "the beginning of the line". Escaping the ^ with \ has the same result. So is it possible to do this using the brackets syntax?

PS: I'm using grep in ADB shell, the grep here may be a little different than in standard *nix systems.

isherwood
  • 58,414
  • 16
  • 114
  • 157
preachers
  • 373
  • 1
  • 5
  • 15
  • 2
    You misplaced `^`, it must be `[^/]`. If you plan to match at the start of string, too, use `(^|[^/])`, and use `-E` option with grep. – Wiktor Stribiżew Mar 28 '23 at 11:50
  • 1
    More, you just can't place anchors inside character classes/bracket expressions. You must use an alternation. – Wiktor Stribiżew Mar 28 '23 at 11:56
  • @Wiktor Stribiżew Thanks! That was simple, I should have thought of that! – preachers Mar 28 '23 at 12:00
  • Starting with `(^|[^/])` would make it unnecessarily complicated to complete the rest of the regexp as `[^/]` will accept any character except `/` so then what do you add on to the regexp after `(^|[^/])` to make it only match `sh` or `/sh` but not `zsh`? Using `(^|[^/])sh` wouldn't work - I actually can't come up with anything that would work i an ERE given that starting point. – Ed Morton Mar 29 '23 at 14:17

2 Answers2

1

Regarding is it possible to do this using the brackets syntax - sure, there's various characters you could put inside a bracket expression but it's not obvious why you'd want to. You should just use:

grep -E '^/?sh'

for this as it means exactly what you say you want - start of line (^) then optional / then sh so it'll match sh or /sh and nothing else.

Regarding:

I'm using grep in ADB shell, the grep here may be a little different than in standard *nix systems.

If your grep is different enough that it doesn't support EREs then use awk instead:

awk '/^\/?sh/'

or (and here's where a bracket expression could be used usefully):

awk '/^[/]?sh/'

Either of those will work using any awk in any shell on every Unix box.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0
echo $'sh\n/sh\nzsh\nbash'
sh
/sh
zsh
bash
grep -E '^/?sh$'   # ERE / PCRE
grep -e '^/\?sh$'  # BRE
sh
/sh
RARE Kpop Manifesto
  • 2,453
  • 3
  • 11
  • 1
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Mar 30 '23 at 10:15