How can I use grep to search for lines that start with a certain character in bash

10,339

Solution 1

The output of alias is lines starting with alias. So your alias should be:

alias ggg='alias | grep "^alias g"'

Solution 2

In zsh,

alias ggg='alias -m "g*"'

Or use a function, so that ggg doesn't print itself:

ggg() alias -m 'g*'

You could also grep the output of "alias", but it may not work properly if there are some multi-line aliases.

With bash, you could use this trick:

(
   alias() { [[ $1 = g* ]] && builtin alias "${1%%=*}"; }
   eval "$(builtin alias)"
)

The idea being that bash's alias outputs some text that is ready to be interpreted to reproduce the same aliases, something like:

$ alias
alias a='foo'
alias goo='gar
baz
alias gro=grar'

So we do evaluate it, but after having redefined alias as a function that calls the real alias only when passed a string that starts with "g".

Solution 3

It depends on your shell, if you are using bash @Dennis is completely right, for zsh it may be another issue if you enabled EXTENDED_GLOB in which case the ^ is interpreted by the shell and you have to quote it, i.e:

alias ggg='alias | grep "^g"'
Share:
10,339

Related videos on Youtube

Michael Durrant
Author by

Michael Durrant

rails ruby rspec rock

Updated on September 18, 2022

Comments

  • Michael Durrant
    Michael Durrant 3 months

    I want an alias ('ggg') that will look through my existing set of aliases and tell me all the ones that begin with g. I have a lot of g* aliases :)

    I tried this: alias ggg='alias | grep ^g' but didn't give me any output (or error). The thing I'm most unsure about is the 'start of line' character.

    • Gilles 'SO- stop being evil'
      Gilles 'SO- stop being evil' about 10 years
      In which shell? What does alias | grep ^g output?
    • Stéphane Chazelas
      Stéphane Chazelas about 10 years
      That code above would work with ksh88, ksh93, pdksh, mksh, ash, dash, zsh, csh, tcsh... but not bash.
    • Michael Durrant
      Michael Durrant about 10 years
      bash (tag added above).
  • Gilles 'SO- stop being evil'
    Gilles 'SO- stop being evil' about 10 years
    True for bash, not for ksh or zsh.
  • Dennis Kaarsemaker
    Dennis Kaarsemaker about 10 years
    Didn't know that as I use bash, thanks for the addition!