问题描述:

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!

网友答案:

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
相关阅读:
Top