我要从此文件中提取匹配的正则表达式:
abc
de
{my_pattern.global} # want to extract my_pattern.global
# without curly brackets
123
并将其分配给shell脚本中的变量:
#!/bin/bash
l_config_file="my_file.cfg"
l_extracted_pattern=""
l_match_pattern="(?<={).+\.global(?=})"
l_my_dir=$(pwd)
echo "grep -oP '$l_match_pattern' $l_my_dir/$l_config_file"
echo "debug 1 - exit code: $?"
grep -oP '$l_match_pattern' $l_my_dir/$l_config_file
echo "debug 2 - exit code: $?"
sh -c "grep -oP '$l_match_pattern' $l_my_dir/$l_config_file"
echo "debug 3 - exit code: $?"
$l_extracted_pattern = "$(sh -c "grep -oP '$l_match_pattern' $l_my_dir/$l_config_file")"
echo "debug 4 - exit code: $?"
echo $l_extracted_pattern
输出:
grep -oP '(?<={).+\.global(?=})' /tmp/my_file.cfg
debug 1 - exit code: 0
debug 2 - exit code: 1
my_pattern.global
debug 3 - exit code: 0
./sto.sh: line 14: =: command not found.
debug 4 - exit code: 127
如您所见,grep命令运行良好(当通过sh -c执行时),但是在尝试将输出分配给具有退出代码127的变量$ l_extracted_pattern时失败。这意味着shell无法识别该命令。我怀疑正则表达式是造成麻烦的原因,但无法弄清楚具体是什么。怎么了?
答案 0 :(得分:0)
即使我之前已经分配了它:
l_extracted_pattern=""
,然后尝试覆盖它:
$l_extracted_pattern = "$(sh -c "grep -oP '$l_match_pattern' $l_my_dir/$l_config_file")"
那是一个错误。显然,bash中的 no 变量赋值可能在变量名之前包含$-甚至早于实例化时也没有。更改为:
l_extracted_pattern = "$(sh -c "grep -oP '$l_match_pattern' $l_my_dir/$l_config_file")"