简体   繁体   English

如何仅将文件中的必要行写入 bash 脚本中的数组?

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

I wrote the following code to read a file and write it in a list using bash script:我编写了以下代码来读取文件并将其写入使用 bash 脚本的列表中:

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

However, I only need to write lines into the array if they contain the word "icon".但是,如果它们包含单词“icon”,我只需要将行写入数组。 An array element should look like this:数组元素应如下所示:

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

Could anyone help me to fix this problem?谁能帮我解决这个问题?

Trivially, with a condition.琐碎,有条件。

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

You should probably fix the syntax to use read -r and the index variable is really unnecessary.您可能应该修复语法以使用read -r并且index变量确实是不必要的。

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

More sensibly, do it all in one fell swoop, in Bash 4+更明智的是,一举搞定,在 Bash 4+

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

Probably most sensibly, if the file really is XML, use an XML parser like xmlstarlet to properly identify and extract the structure you want to examine.可能最明智的是,如果文件确实是 XML,请使用 XML 解析器(如xmlstarlet )正确识别和提取您要检查的结构。

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

You can use regex:您可以使用正则表达式:

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