Let's say I have a file which has some ls -l output:

waaa- foo.pdf
-bbb- foobar.pdf
-ccc- foobar
waaa- foobar

I'd like to get just the first line

waaa -foo.pdf

as the final result, and I'm trying:

egrep -E "^w" .file | egrep -E "*.pdf"

Is there any way to combine these two searches?

  • 1
    Did you actually get ls to display a mode string starting with w? As far as I know w only appears in other positions in a mode string (where it means "writable"). It's totally fine if you didn't and this is just a regex example. But if it also represents a real situation then it might be valuable to have additional answers showing alternatives to parsing the output of ls, like using find with the -perm and -name tests and the -ls action. Jul 29, 2017 at 21:18
  • I don't think this is really a duplicate of Grep searching two words in a line, which is about grepping for lines with two words appearing anywhere, and in either order. In this question, the line must begin in a specific way and end in a specific way. Aug 2, 2017 at 17:54

1 Answer 1


You have to write it like:

egrep "^w.*\.pdf$" filename
  • Means started with w followed by any character and ended to .pdf.

for a logical "or" you can use -e switch:

egrep -e pattern1 -e pattern2

means all lines with pattern1 or pattern2.

or as @steeldriver suggested, use extended regex "or":

egrep "(pattern1|pattern2)"

and as you know for extended regular expressions you have to use egrep and not grep, e.g:

egrep '(bbb|ccc)' # works fine for your file
grep '(bbb|ccc)' # doens't have any result

For an "and" you have to pipe it to another egrep:

grep pattern1 | grep pattern2

means all lines with both pattern1 and pattern2.

or use another tools like awk:

awk '/pattern1/ && /pattern2/` filename
  • in this command ""egrep "^w.*\.pdf$" filename" meaning of ( \ ) is "and"?
    – solfish
    Jul 29, 2017 at 20:28
  • No, \ is used to escape the dot (.), dot . means any char and \. means exactly a dot ..
    – Ravexina
    Jul 29, 2017 at 20:29
  • first command better, i dont have any knowladge awk yet:)
    – solfish
    Jul 29, 2017 at 20:36
  • 1
    Note that you can use | as a simple logical OR in grep extended regular expression (ERE) syntax (or, equivalently, \| in BRE) e.g. egrep '(pat|mat)' and grep '\(pat\|mat\)' are both equivalent to grep -e pat -e mat Jul 29, 2017 at 20:41
  • @steeldriver Yeah, however that's a part of regex and -e is a grep functionality itself right?
    – Ravexina
    Jul 29, 2017 at 20:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.