How can I use grep to search for lines that start with a certain character in bash
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"'
Related videos on Youtube

Comments
-
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' about 10 yearsIn which shell? What does
alias | grep ^g
output? -
Stéphane Chazelas about 10 yearsThat code above would work with ksh88, ksh93, pdksh, mksh, ash, dash, zsh, csh, tcsh... but not bash.
-
Michael Durrant about 10 yearsbash (tag added above).
-
-
Gilles 'SO- stop being evil' about 10 yearsTrue for bash, not for ksh or zsh.
-
Dennis Kaarsemaker about 10 yearsDidn't know that as I use bash, thanks for the addition!