2011-04-13 53 views
0

以下是我写处理从一个字符串数组通配符扩展在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”从数组中检索时打印而不是文件名?

回答

2

假设bash的是正确的工具,有几个方面:

  1. 禁用filename expansion暂时
  2. 使用read与IFS
  3. 使用bash expansion

禁用扩展的替换功能:

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" 
+0

它适用于我,我将使用第二种解决方案。感谢Mikel! – ranjit 2011-04-13 06:18:57

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> 
+0

没有工作马克。通配符的问题发生在我拆分字符串时,将其分配给一个数组,并尝试从数组中检索它并显示! – ranjit 2011-04-13 06:15:31