[英]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.