2011-04-13 82 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