如何解决在bash shell脚本中处理字符串数组中的通配符扩展
|| 以下是我编写的示例脚本line=\"/path/IntegrationFilter.java:150: * <td>http://abcd.com/index.do</td>\"
echo \"$line\" <-- \"$line\" prints the text correctly
result_array=( `echo \"$line\"| sed \'s/:/\\n/1\' | sed \'s/:/\\n/1\'`)
echo \"${result_array[0]}\"
echo \"${result_array[1]}\"
echo \"${result_array[2]}\" <-- prints the first filename in the directory due to wildcard character * .
从数组中检索文本时,如何获取文本\“ * http://abcd.com/index.do \”而不是文件名?
解决方法
假设bash是正确的工具,有几种方法:
暂时禁用文件名扩展
使用IFS读取
使用bash扩展的替代功能
禁用扩展:
line=\"/path/IntegrationFilter.java:150: * <td>http://abcd.com/index.do</td>\"
set -f
OIFS=$IFS
IFS=$\'\\n\'
result_array=( `echo \"$line\"| sed \'s/:/\\n/1\' | sed \'s/:/\\n/1\'`)
IFS=$OIFS
set +f
echo \"${result_array[0]}\"
echo \"${result_array[1]}\"
echo \"${result_array[2]}\"
(请注意,我们还必须设置IFS,否则内容的每个部分都以result_array [2],[3],[4]等结尾)
使用读取:
line=\"/path/IntegrationFilter.java:150: * <td>http://abcd.com/index.do</td>\"
echo \"$line\"
IFS=: read file number match <<<\"$line\"
echo \"$file\"
echo \"$number\"
echo \"$match\"
使用bash参数扩展/替换:
line=\"/path/IntegrationFilter.java:150: * <td>http://abcd.com/index.do</td>\"
rest=\"$line\"
file=${rest%%:*}
[ \"$file\" = \"$line\" ] && echo \"Error\"
rest=${line#$file:}
number=${rest%%:*}
[ \"$number\" = \"$rest\" ] && echo \"Error\"
rest=${rest#$number:}
match=$rest
echo \"$file\"
echo \"$number\"
echo \"$match\"
,怎么样:
$ line=\'/path/IntegrationFilter.java:150: * <td>http://abcd.com/index.do</td>\'
$ echo \"$line\" | cut -d: -f3-
* <td>http://abcd.com/index.do</td>