簡體   English   中英

在bash shell腳本中處理字符串數組中的通配符擴展

[英]Handling wildcard expansion from a string array in a bash shell scripting

以下是我編寫的示例腳本

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是正確的工具,有幾種方法:

  1. 暫時禁用文件名擴展
  2. 使用IFS 讀取
  3. 使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM