读取文本文件以填充bash中的数组
发布时间:2020-12-15 20:55:08 所属栏目:安全 来源:网络整理
导读:参见英文答案 Why equal to operator does not work if it is not surrounded by space?????????????????????????????????????4个 ???????????? How do I compare two string variables in an ‘if’ statement in Bash? ??????????????????????????????????
参见英文答案 >
Why equal to operator does not work if it is not surrounded by space?????????????????????????????????????4个
>???????????? How do I compare two string variables in an ‘if’ statement in Bash? ????????????????????????????????????12个 我有一个输入文本文件,如下所示: # string name | String type (x,y,or z) name_1 | x name_2 | y name_3 | z 我想读它并填写 >包含所有字符串名称的全局数组 这是我的脚本: # Array initialization list_global=();list_x=();list_y=();list_z=() # Remove blank lines if there are some sed -i '/^[[:space:]]*$/d' input_tab.txt # Reading file while read line do name=$(echo $line |awk -F "|" '{print $1}'|sed 's/ //g') type=$(echo $line |awk -F "|" '{print $2}'|sed 's/ //g') # Checking data are correctly read printf "%6s is of type %2s n" "$name" "$type" # Appending to arrays list_global+=("$name") if [ "$type"==x ] then list_x+=("$name") elif [ "$type"==y ] then list_y+=("$name") elif [ "$type"==z ] then list_z+=("$name") fi done < input_tab.txt # Print outcome echo global_list ${list_global[@]} echo -e "n n n " echo list_x ${list_x[@]} echo list_y ${list_y[@]} echo list_z ${list_z[@]} 这会产生以下输出 name_1 is of type x name_2 is of type y name_3 is of type z global_list name_1 name_2 name_3 list_x name_1 name_2 name_3 list_y list_z 这意味着我的输入文件被正确读取,并且我填充数组的方式是有效的. 笔记: >使用开关/盒而不是if导致相同的结果 任何帮助/解释将不胜感激, 解决方法
这段代码将解决问题的问题,实际上我所改变的语法是if条件而不是:
if [ "$type"==x ] 现在看起来像: if [ "$type" == "x" ] 所以在你的情况下,使用你的sytax,if条件将始终评估为真,这就是为什么它将它全部放到第一个列表中. # Array initialization list_global=();list_x=();list_y=();list_z=() # Remove blank lines if there are some sed -i '/^[[:space:]]*$/d' remo.txt # Reading file while read line do name=$(echo $line |awk -F "|" '{print $1}'|sed 's/ //g') type=$(echo $line |awk -F "|" '{print $2}'|sed 's/ //g') # Checking data are correctly read printf "%6s is of type %2s n" "$name" "$type" # Appending to arrays list_global+=("$name") if [ "$type" == "x" ] then list_x+=("$name") elif [ "$type" == "y" ] then list_y+=("$name") elif [ "$type" == "z" ] then list_z+=("$name") fi done < remo.txt # Print outcome echo global_list ${list_global[@]} echo -e "n n n " echo list_x ${list_x[@]} echo list_y ${list_y[@]} echo list_z ${list_z[@]} 输出将是: list_x name_1 list_y name_2 list_z name_3 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |