Search code examples
regexgrepadb

How can I match two characters with an optional leading slash?


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.


Solution

  • 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.