在Shell脚本中将SED Commnd的字符串输出存储在数组中 [英] Storing String Output of SED Commnd in an Array In Shell Script
问题描述
我有一个XML文件,格式为:
< classes>
< subject lb = Fall Sem 2020>
< name>操作系统< / name>
< credit> 3< / credit>
< type>理论< / type>
< faculty>教授XYZ< faculty>
< / subject>
< subject lb = Spring Sem 2020>
< name> Web开发< / name>
< credit> 3< / credit>
< type> Lab< / type>
< / subject>
< subject lb = Fall Sem 2021>
< name>计算机网络< / name>
< credit> 3< / credit>
< type>理论< / type>
< faculty>教授ABC<院系>
< / subject>
< subject lb = Spring Sem 2021>
< name>软件工程< / name>
< credit> 3< / credit>
< type> Lab< / type>
< / subject>
< / classes>
我可以使用 sed $ c获得所需的结果$ c>命令。即
sed -En's /.* lb =([^] +)。* / \1 / p'文件
输出:
2020年秋季学期
2020年春季学期
秋季学期2021
春季学期2021
我希望此输出存储在数组中。 $ b ie
arr [0] = Fall Sem 2020
我的尝试:
arr =($(sed -En's /.* lb =([[^] +)。* / \1 / p'文件))
但是,在这种情况下,我将单个元素作为数组元素。即
arr [0] =秋天
解决方案可以请尝试以下操作(考虑到OP没有xml工具,也无法安装它们)。
IFS =','; array =($(
awk'
BEGIN {OFS =,}
/< subject lb = / {
match($ 0,/ 。* /)
val =(val?val OFS:)substr($ 0,RSTART + 1,RLENGTH-2)
}
END {
print val
}'Input_file))
打印数组的所有元素使用:
echo $ {array [@]}
Fall Sem 2020 Spring Sem 2020秋季Sem 2021春季Sem 2021
要打印特定元素,请使用:
echo $ {array [0]}
2020年秋季学期
I have an XML file of the format:
<classes> <subject lb="Fall Sem 2020"> <name>Operating System</name> <credit>3</credit> <type>Theory</type> <faculty>Prof. XYZ</faculty> </subject> <subject lb="Spring Sem 2020"> <name>Web Development</name> <credit>3</credit> <type>Lab</type> </subject> <subject lb="Fall Sem 2021"> <name>Computer Network</name> <credit>3</credit> <type>Theory</type> <faculty>Prof. ABC</faculty> </subject> <subject lb="Spring Sem 2021"> <name>Software Engineering</name> <credit>3</credit> <type>Lab</type> </subject> </classes>
I'm able to get the desired result using
sed
command. i.e.sed -En 's/.* lb="([^"]+)".*/\1/p' file
Output:
Fall Sem 2020 Spring Sem 2020 Fall Sem 2021 Spring Sem 2021
I want this output to be stored in an array. i.e.
arr[0]="Fall Sem 2020"
My try:
arr=($(sed -En 's/.* lb="([^"]+)".*/\1/p' file))
But in this case, I'm getting individual element as an array element. i.e.arr[0]="Fall"
解决方案Could you please try following(considering that OP doesn't have xml tools and can't install them too).
IFS=',';array=( $( awk ' BEGIN{ OFS="," } /<subject lb="/{ match($0,/".*"/) val=(val?val OFS:"")substr($0,RSTART+1,RLENGTH-2) } END{ print val }' Input_file))
To print all elements of array use:
echo ${array[@]} Fall Sem 2020 Spring Sem 2020 Fall Sem 2021 Spring Sem 2021
To print specific element use:
echo ${array[0]} Fall Sem 2020
这篇关于在Shell脚本中将SED Commnd的字符串输出存储在数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!