Home > Software design >  How to filter variable pattern strings using regular expressions
How to filter variable pattern strings using regular expressions

Time:12-29

I have bunch of lines in a file as below

dir_1/sec_dir          700  600
dir_1/sec_dir/file1    400  500
dir_1/sec_dir/file2    300  100
dir_2/tri_dir          300  1600
dir_2/tri_dir/file1    100  1500
dir_2/tri_dir/file2    200  100

I need to use a regular expression to grep "only" the 2 lines below (and not the rest) from the above 6 lines

dir_1/sec_dir          700  600
dir_2/tri_dir          300  1600

I tried regular expression => dir_[0-9]\/[a-z].*\s [0-9]

The above regular expression yields nothing. What's wrong here ?

CodePudding user response:

You are matching only a single char a-z and no underscores, but the .* after if matches the rest of the line.

You can restrict the match to chars a-z and _ and match spaces and again digits at the end.

dir_[0-9]/[a-z_] \s [0-9] \s [0-9]*

Regex demo

CodePudding user response:

Your question is ambiguous. One possible solution:

(?<=.*\/)\w _dir  \d   \d 

gives back:

sec_dir          700  600
tri_dir          300  1600

Live demo and regex explanation

  • Related