我有一个名为mail_status.txt的文件。文件的内容如下。
1~auth_flag~
2~download_flag~
3~copy_flag~
4~auth_flag~
5~auth_flag~
6~copy_flag~
我想对该文件执行一些操作,以便最后我应该获得三个变量,它们各自的值如下:
auth_flag_ids="1,4,5"
download_flag_ids="2"
copy_flag_ids="3,6"
我对这种语言很陌生。如果需要更多详细信息,请告诉我。
谢谢
答案 0 :(得分:1)
如果您要根据文件内容生成bash
变量,
请尝试以下操作:
# read the file and extract information line by line
declare -A hash # delcare hash as an associative array
while IFS= read -r line; do
key="${line#*~}" # convert "1~auth_flag~" to "auth_flag~"
key="${key%~*}_ids" # convert "auth_flag~" to "auth_flag_ids"
hash[$key]+="${line%%~*}," # append the value to the hash
done < "mail_status.txt"
# iterate over the hash to create variables
for r in "${!hash[@]}"; do # r is assigned to "auth_flag_ids", "download_flag_ids" and "copy_flag_ids" in tern
printf -v "$r" "%s" "${hash[$r]%,}" # create a variable named "$r" and assign it to the hash value by trimming the trailing comma off
done
# check the result
printf "%s=\"%s\"\n" "auth_flag_ids" "$auth_flag_ids"
printf "%s=\"%s\"\n" "download_flag_ids" "$download_flag_ids"
printf "%s=\"%s\"\n" "copy_flag_ids" "$copy_flag_ids"
hash
中。hash
的键以创建名称为
“ auth_flag_ids”,“ download_flag_ids”和“ copy_flag_ids”。printf -v var
创建一个变量var
。此机制有助于引起
间接引用变量。我不会详细解释bash
特定的符号
例如${parameter#word}
,${parameter%%word}
或${!name[@]}
。
您可以轻松找到参考资料和说明清楚的文档,包括
bash手册页。
希望这会有所帮助。