在shell脚本中的字符串中查找子字符串无效
我有一个test.cfg文件,其内容如下:在shell脚本中的字符串中查找子字符串无效,shell,unix,Shell,Unix,我有一个test.cfg文件,其内容如下: product_identifier=XR656_HD;G6_656 program_family=STR 和一个脚本文件作为 #!/bin/bash CONFIG_FILE="test.cfg" getValueforKeyInProdConfig () { key=$1 if [ -e $CONFIG_FILE ]; then value=`cat $CONF
product_identifier=XR656_HD;G6_656
program_family=STR
和一个脚本文件作为
#!/bin/bash
CONFIG_FILE="test.cfg"
getValueforKeyInProdConfig ()
{
key=$1
if [ -e $CONFIG_FILE ]; then
value=`cat $CONFIG_FILE | grep $key | cut -d "=" -f2 | tr -d '\r'`
echo "$value"
else
echo ""
fi
}
product_identifier="$(getValueforKeyInProdConfig "product_identifier")"
program_family="$(getValueforKeyInProdConfig "program_family")"
echo "product_identifier=$product_identifier"
echo "program_family=$program_family"
if [[ ( $program_family == "STR" ) && ( ($product_identifier == *"G6_656"*) || ($product_identifier == *"G6_646"*) ) ]]; then
echo "found string"
else
echo "unknown"
fi
但结果是:
product_identifier=XR656_HD;G6_656
program_family=STR
unknown
我希望输出是
found string
我应该如何比较bash中的子字符串以使脚本工作为什么不直接为配置文件提供源代码
$ cat test.cfg
product_identifier='XR656_HD;G6_656'
program_family=STR
剧本
#!/bin/bash
CONFIG_FILE="test.cfg"
. "$CONFIG_FILE"
echo product_identifier=$product_identifier
echo program_family=$program_family
[[ $program_family == "STR" ]] && \
[[ $product_identifier =~ .*G6_6[45]6 ]] && \
echo "found string" || echo "unknown"
测试
$ ./test
product_identifier=XR656_HD;G6_646
program_family=STR
found string
$ ./test
product_identifier=XR656_HD;G6_656
program_family=STR
found string
$ ./test
product_identifier=XR656_HD;G6_676
program_family=STR
unknown
$ ./test
product_identifier=XR656_HD;G6_656
program_family=fail
unknown
我按原样运行了这个程序,它(在Mac上)对我有效。我得到:
product_identifier=XR656_HD;G6_656 program_family=STR找到字符串
您能在另一台机器上试用吗?value=$(grep$key);value=“${value##*=}”代码>(删除子字符串的参数扩展)问题与空格有关,因为cfg文件第一行后面有空格,所以无法工作