janu777
janu777

Reputation: 1978

how to exclude certain pattern when searching in bash

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?

Upvotes: 1

Views: 155

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

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]\+$

Upvotes: 2

Nic3500
Nic3500

Reputation: 8591

Let's say the data in put in a file, data.txt

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

The command to get the last two lines is:

grep -E '*[0-9]$' data.txt

Explanation:

  • -E, the pattern is interpreted as an extended regular expression.
  • *: any character
  • [0-9]: one digit
  • $: ends with the character just before the $. So here, it indicates that the string must end with a digit.

So it looks at the lines in data.txt, and outputs the lines where the last character is a digit, from 0 to 9.

Upvotes: 1

Related Questions