Saturday, April 9, 2022

[SOLVED] how to exclude certain pattern when searching in bash

Issue

Let's say I have

 abc-def1-xxx
 abc-def2-yy-vv
 abc-def3
 abc-def4

I want to output abc-def3 and abc-def4

If I use the pattern abc-def* then it outputs everything. If I search for abc-def*-* then it out puts the first two entries How do I get the last two entries?


Solution

You can make the pattern more specific matching lowercase chars with a hyphen and matching 1 or more digits at the end

  • ^ Start of string
  • [a-z]\+ Match 1+ chars a-z
  • - Match literally
  • [a-z]\+ Match 1+ chars a-z
  • [0-9]\+ Match 1+ digits
  • $ End of string

For example

echo "abc-def1-xxx
abc-def2-yy-vv
abc-def3
abc-def4" | grep '^[a-z]\+-[a-z]\+[0-9]\+$'

Output

abc-def3
abc-def4

You could also match for example abc-def and then 1 or more digits:

^abc-def[0-9]\+$


Answered By - The fourth bird
Answer Checked By - Willingham (WPSolving Volunteer)