Mensch Mensch - 1 year ago 70
Linux Question

Grep a filename with a specific underscore pattern

I am trying to grep a pattern from files using egrep and regex without success.

What I need is to get a file with for example a convention name of:


The code should have at least 3 digits, the lastname and firstname and city can vary on size

I am trying the code below but it fails to achieve what I desire:

ls -1 | grep -E "[xx_][A-Za-z]{3,}[_][A-Za-z]{2,}[_][A-Za-z]{2,}[_][A-Za-z]{2,}[.][doc|pdf]"

That is trying to get the standard xx_ from the beggining, then any code that has at least 3 words and after that it must have another underscore, and so on.
Could anybody help ?

Answer Source

Consider an extglob, as follows:

shopt -s extglob # turn on extended globbing syntax

files=( xx_[[:alpha:]][[:alpha:]]+([[:alpha:]])_[[:alpha:]]+([[:alpha:]])_[[:alpha:]]+([[:alpha:]])_[[:alpha:]]+([[:alpha:]]).@(doc|docx|pdf) )

[[ -e ${files[0]} ]] || -L ${files[0]} ]] && printf '%s\n' "${files[@]}"

This works because


...matches any string of three or more alpha characters -- two of them explicitly, one of them with the +() one-or-more extglob syntax.



...matches any of these three specific strings.