我是 bash 新手,不熟悉。我试图移动一个文件,其中的数据由空格和“,”分隔,并将信息存储到列表中。 bash 唯一的容器似乎是一个数组。如有任何帮助,我们将不胜感激。
假设我有一个名为 example.txt 的文件,其中包含用户名、密码和出生率,并且想要迭代并将用户、密码和出生日期存储在单独的列表中,那么完成此操作的最简单方法是什么
样本.txt
user1, password1, 081192
user2, password2, 092578
user3, password3, 020564
最佳答案
Bash 版本 4 有关联数组,我认为这正是您正在寻找的。p>
请注意,您需要大量嘈杂的语法(大括号、方括号和引号)才能在 bash 中处理数组。
IFS+="," # add comma to the list of characters for word splitting
# you now cannot use a comma in your passwords.
declare -A passwords ids # 2 associative arrays
while read -r user password id; do
passwords["$user"]=$password
ids["$user"]=$id
done < sample.txt
# now that they are stored, let's print them out:
# iterate over the keys of the ids array
for user in "${!ids[@]}"; do
printf "%s:%s:%s\n" "$user" "${passwords["$user"]}" "${ids["$user"]}"
done
我将提供一些 bash 手册中文档的链接:它是非常密集的阅读,但却是 bash 智慧的源泉。
- read命令
- shell 如何使用 IFS 变量将文本拆分为单词:Word Splitting
- shell 扩展的顺序是 here
- bash arrays
关于linux - 在 bash 中迭代数据文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31679738/