在bash shell脚本中处理字符串数组中的通配符扩展

时间:2011-04-13 05:41:16

标签: bash shell unix

以下是我编写的示例脚本

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”而不是文件名?

2 个答案:

答案 0 :(得分:2)

假设bash是正确的工具,有几种方法:

  1. 暂时停用filename expansion
  2. read与IFS一起使用
  3. 使用bash expansion
  4. 的替换功能

    禁用扩展:

    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"
    

答案 1 :(得分:0)

怎么样:

$ line='/path/IntegrationFilter.java:150:         * <td>http://abcd.com/index.do</td>'

$ echo "$line" | cut -d: -f3-
* <td>http://abcd.com/index.do</td>
相关问题