簡體   English   中英

如何僅將文件中的必要行寫入 bash 腳本中的數組?

[英]How to write only necessary lines from a file into an array in bash script?

我編寫了以下代碼來讀取文件並將其寫入使用 bash 腳本的列表中:

index=0
while read line
do
  array[$index]="$line"
  index=$(($index+1))
done < ../../file.xml

但是,如果它們包含單詞“icon”,我只需要將行寫入數組。 數組元素應如下所示:

<icon height="36" width="36" density="ldpi" src="res/icon/android/ldpi.png"/>

誰能幫我解決這個問題?

瑣碎,有條件。

case $line in *icon*) ... do stuff;;

您可能應該修復語法以使用read -r並且index變量確實是不必要的。

array=()
while read -r line
do
  case $line in *icon*) array+=("$line");; esac
done < ../../file.xml

更明智的是,一舉搞定,在 Bash 4+

readarray index < <(grep 'icon'  ../../file.xml)

可能最明智的是,如果文件確實是 XML,請使用 XML 解析器(如xmlstarlet )正確識別和提取您要檢查的結構。

readarray index < <(xmlstarlet sel -t -m //icon -c . -n ../../file.xml)

您可以使用正則表達式:

regex="icon"
index=0
while read line
do
  if [[ $line =~ $regex ]]; then
    array[$index]="$line"
    #If you need cut address uncommend next line and comment before line
    #array[$index]="$(sed 's/.*src=\"\(.*\)\".*/\1/' <<< $line)"
    index=$(($index+1))
  fi
done < ../../file.xml

暫無
暫無

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

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