gpt4 book ai didi

arrays - bash:找到文件中的所有正则表达式并放入数组

转载 作者:行者123 更新时间:2023-11-29 09:50:59 25 4
gpt4 key购买 nike

我有一个包含 PlaceHolders 的模板配置文件,我想找到所有这些 PlaceHolders 并将其放入一个数组中。

当前状态:
仅当超过一个 PlaceHolder时,我才能在文件中找到所有PlaceHolder。

例如,这是我的模板文件:

upstream portal {        
server {{UNICORN_SERVICE_NAME}}:{{UNICORN_SERVICE_PORT}};
}

server {
listen *:80 default_server;
server_name {{APP_HOST}};
server_tokens off;
root /dev/null;

# Increase this if you want to upload large attachments
# Or if you want to accept large git objects over http
client_max_body_size {{NGINX_MAX_UPLOAD_SIZE}};

location {{GITLAB_RELATIVE_URL_ROOT}}/ {
root /var/lib/nginx/portal;
# serve static files from defined root folder;.
# @gitlab is a named location for the upstream fallback, see below
}
}

这是我用来查找占位符的代码:

matches_bloc=$(awk 'match($0, /(\{\{)([^{]*)(\}\})/) {
print substr($0, RSTART, RLENGTH)
}' ${currFile})

# convert 'matches_bloc' into array
matches=()
echo "Matches:"
while read -r line; do
matches+=("$line")
echo " - ${line}"
done <<< "$matches_bloc"

在此示例中,匹配结果将是:

Matches:
- {{UNICORN_SERVICE_NAME}}
- {{APP_HOST}}
- {{NGINX_MAX_UPLOAD_SIZE}}
- {{GITLAB_RELATIVE_URL_ROOT}}

您可以注意到文件中有 5 个 PlaceHolder,但只有 4 个匹配项。
缺少的匹配项是:{{UNICORN_SERVICE_PORT}},因为同一行中已经有另一个匹配项。

我的问题是:
我怎样才能找到文件中的所有匹配项而不考虑行?

最佳答案

找到模板文件中的所有变量并将它们放入一个数组中。

GNU grep :

array=( $(grep -Po '{{.*?}}' file) )
declare -p array

输出:

declare -a array='([0]="{{UNICORN_SERVICE_NAME}}" [1]="{{UNICORN_SERVICE_PORT}}" [2]="{{APP_HOST}}" [3]="{{NGINX_MAX_UPLOAD_SIZE}}" [4]="{{GITLAB_RELATIVE_URL_ROOT}}")'

-P: Interpret {{.*?}} as a Perl regular expression.

-o: Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

* The preceding expression can match zero or more times. With ? the * tries to match as few as possible (non-greedy).


参见:The Stack Overflow Regular Expressions FAQ

关于arrays - bash:找到文件中的所有正则表达式并放入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44354619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com