Daniel_H
Daniel_H

Reputation: 105

grep regex return substring but exclude comments

I want to get a substring from a file, but only from lines which are not preceded by an exclamation mark (which is the comment symbol in Fortran). I would prefer to use grep (but not bound to). For example:

infile.txt:

calib_ss/baseline.txt
!calib_ss/base_sharpe.txt

Desired result:

baseline

I got this far:

grep -Po "(?<=/)[^/.]*(?=\.)" infile.txt

which returns

baseline
base_sharpe

To exclude the lines starting with ! I thought of combining the expression with

^[^\!]

but I don't manage. Thanks in advance!

Upvotes: 5

Views: 502

Answers (1)

anubhava
anubhava

Reputation: 785128

This grep should work:

grep -Po '^[^!].*?(?<=/)\K[^/.]*(?=\.)' infile.txt

OUTPUT:

baseline

Explanation:

  • ^[^!] will make sure to match anything but ! at line start
  • \K will make sure to reset the start

Upvotes: 4

Related Questions