0

I have a file where I want to extract all matches.

  1. Each match starts with a word, and ends with the nth time a character occurs after each match, in this case 2nd.
  2. Include in the output the word and nth matching character.
  3. Output one match per line.
  4. There can be any number of matches on any line.
  5. Each match is in the same line: meaning a match is not split between two lines with CR, LF, CRLF.

Example: extract all matches between 'user' and 2nd match of '-' after each 'user':

Input file:

sample text user=data-no value /) xx- fdfd\n
abcd

abcd user-- example$% user-%&?@:-useruser**-#<>\"-user0-
gg-
--
useruser------data
user-user------data

Output file prioritizing the starting match (word) and then search forward:

user=data-no value /) xx-
user--
user-%&?@:-
useruser**-#<>\"-
useruser--
user-user-

Output file prioritizing the ending nth match (word) and read backwards:

user=data-no value /) xx-
user--
user-%&?@:-
user**-#<>\"-
user--
user-user-

1 Answer 1

0

I don't understand what "prioritizing" means in this context, but you could use a simple grep:

$ grep -Eo 'user([^-]*-){2}' file
user=data-no value /) xx-
user--
user-%&?@:-
useruser**-#<>\"-
useruser--
user-user-

([^-]*-){2} matches a (possibly empty) sequence of non-hyphen characters followed by a hyphen character, twice.

1
  • Prioritizing means what you search first for. If you prioritize user, you first search for it, then search for 2n '-' forward. If you prioritize the two '-', you look for it, and then search back for more contiguous 'user'. I think it's clean on the example.
    – Smeterlink
    Commented Apr 11, 2020 at 12:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .