0

I have a list of files in a directory and I want to build a simple regex to grep the filesname starting from first underscore position '_' and in between first '-'.

For example:

2180_PP AAA Radius Statistic-42005_04May2020_0900-04May2020_1000.csv
2180_SW Interface  Flow(3GPP AAA)-53448_14May2020_0000-14May2020_0100.csv

Expected file names would be like:

PP AAA Radius Statistic
SW Interface  Flow(3GPP AAA)

I have found similar pattern but no exactly working in my case.

echo 2180_SW Interface  Flow(3GPP AAA)-53448_14May2020_0000-14May2020_0100.csv | grep -oP '(?<=_)\d+(?=\-)'
1

man grep says

  grep searches for PATTERNS in each FILE.  PATTERNS is one or patterns separated by newline characters, and grep prints each line that matches a pattern.

 -o, --only-matching
              Print  only  the  matched  (non-empty) parts of a matching line,
              with each such part on a separate output line.

 -P, --perl-regexp
              Interpret   PATTERNS   as  Perl-compatible  regular  expressions
              (PCREs).  This option is experimental when combined with the  -z
              (--null-data)  option,  and  grep  -P  may warn of unimplemented features.

On ls i had

'2180_PP AAA Radius Statistic-42005_04May2020_0900-04May2020_1000.csv'
'2180_SW Interface  Flow(3GPP AAA)-53448_14May2020_0000-14May2020_0100.csv'

After running the below code, I got

ls | grep -oP '(?<=_).*(?=\-\d\d\d)'
PP AAA Radius Statistic
SW Interface  Flow(3GPP AAA)

Explanation of REGEX

(?<= - Stands for a positive look-behind and will not include the words before it

.    - Matches any characters except line break

(?=  - Stands for positive look-ahead. Matches a group 
       after the main result without including it in the result.

\-   - Matched character -

\d   - Matched digit

Source of REGEX explanation is REGEXR

Why possibly you got a different result?

Was that there was another matching - in the input (-14May). So I used \-\d\d\d to counteract that.

| improve this answer | |
  • Yes I will like to help. But i see that the solution to that question has been made. I could not get the exact point where you are stuck. So if you could kind of try once with the solution mentioned and if you are not able to solve, create a new question with the requirement @vikrantrana – Praveen Kumar-M May 17 at 7:53
  • OK partly understanding your query. But not fully. Also the community rules does not allow to discuss in comments a long. So try and if you are not able to do, please post as a new query (checking whether such a question has not been asked before) – Praveen Kumar-M May 17 at 8:00

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.