如何在匹配文件内的字符后获得下一个单词

问题描述 投票:1回答:1

我一直在寻找解决方案herehere,但没有运气,我找到了一个与我讨论类似情况的线程,最后我决定在这里提出一个问题,因为它没有提供我面对的案例的解决方案。

如何使用bash脚本在Python脚本(params的值)中获得某个单词?例如,我有一个Python脚本,它具有以下代码:

from datetime import datetime, timedelta
from airflow import DAG
...


args = {
    ...
}

# A DAG for my_bigquery_pipeline -> this line should not be included in bash searching.
with DAG(dag_id='my_bigquery_pipeline', default_args=args,
         schedule_interval='00 21 * * *') as dag:

从上面的脚本我想得到my_bigquery_pipeline这个词没有注释,在我问这里之前,我已经用以下方式尝试了它:

sed -n '/^.*dag_id\s\+\/\(\w\+\).*$/s//\1/p' bigquery_pipeline.py
// and
sed "s/dag_id//2g" bigquery_pipeline.py
// and
egrep -oP '(?<=dag_id=/)\w+' bigquery_pipeline.py

不幸的是,这些方法对我不起作用,任何帮助我都会感激!谢谢!。

shell sed grep sh
1个回答
1
投票

egrep等于grep -E,所以它会与-P开关冲突。 如果你有GNU grep,你可以这样做:

grep -oP '(?<=dag_id=.)\w+' bigquery_pipeline.py

或更确切地说:

grep -oP '(?<=dag_id=\x27)\w+' bigquery_pipeline.py

其中0x27'的ascii代码。 您还可以更改外部引号,如下所示:

grep -oP "(?<=dag_id=')\w+" bigquery_pipeline.py

或者这与你的.py代码方式更兼容:

 grep -oP 'dag_id\s*=\s*[\x27\x22]\K\w+' bigquery_pipeline.py

哪个也匹配dag_id = "my_bigquery_pipeline",并给结果my_bigquery_pipeline

sed解决方案:

sed -n '/^.*dag_id *= *[[:punct:]]\([[:alnum:]_]*\).*/s//\1/p' bigquery_pipeline.py
my_bigquery_pipeline

为避免评论行:

grep -oP '^\s*[^#]+.*dag_id\s*=\s*[\x27\x22]\K\w+' bigquery_pipeline.py

要么

sed -n '/^[^#]*dag_id *= *[[:punct:]]\([[:alnum:]_]*\).*/s//\1/p' bigquery_pipeline.py

perl解决方案的可选dag_id=,也忽略注释行:

perl -nle 'print $& while m{[^#]*with DAG\((dag\s*=\s*)?[\x27\x22]\K\w+}g' bigquery_pipeline.py
© www.soinside.com 2019 - 2024. All rights reserved.