Score:0

why grep with regex command not working on Ubuntu

cn flag

I wanted to know the packages which are installed and starting with mos then below command not working.

dpkg -l | grep  ^mos*
Score:3
hr flag

Although ^mos* is a perfectly cromulent grep Basic regular Expression (BRE), it likely doesn't mean what you think it means. You should also get into the habit of quoting any pattern that you pass to grep, so that the shell does not try to expand it to a list of filenames in the current directory.1

* in a regular expression is a quantifier rather than a wildcard, so mos* means m o then zero or more s characters. The regex equivalent of the shell wildcard * would be .* (any character, zero or more times). However since grep by default outputs the whole line even when the match is partial, a trailing .* is superfluous - ^mos would do as well as ^mos.*

However ^ anchors a regular expression to the start of a line - and dpkg -l outputs the package's status before its name, so ^mos will never match in this context.

You could use ^.. *mos to match two arbitrary status characters anchored to start-of-line, followed by one or more spaces before mos:

$ dpkg -l | grep '^..  *mos'
ii  most                                      5.0.0a-4                                       amd64        Pager program similar to more and less

however I'd suggest using awk instead of grep for this task, since you can match against specific fields ex.

$ dpkg -l | awk '$2 ~ /^mos/'
ii  most                                      5.0.0a-4                                      amd64        Pager program similar to more and less

or if you want to output only matching installed packages for example

dpkg -l | awk '$1 == "ii" && $2 ~ /^mos/'

  1. or at least to stop relying on the shell to pass the literal value of the pattern to grep when it does not match - although bash does so by default, other shells (zsh in particular) don't.
Score:2
cn flag

To get grep use regex add -E switch this way:

dpkg -l | grep -E '^mos.*'

But this won't give you any results, because dpkg -l lines start with ii and other chars.

You can try this one:

apt list --installed | grep -E '^mos.*'
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.