linux - 在 bash 中迭代数据文件

标签 linux bash shell command-line

我是 bash 新手,不熟悉。我试图移动一个文件,其中的数据由空格和“,”分隔,并将信息存储到列表中。 bash 唯一的容器似乎是一个数组。如有任何帮助,我们将不胜感激。

假设我有一个名为 example.txt 的文件,其中包含用户名、密码和出生率,并且想要迭代并将用户、密码和出生日期存储在单独的列表中,那么完成此操作的最简单方法是什么

样本.txt

user1, password1, 081192
user2, password2, 092578
user3, password3, 020564

最佳答案

Bash 版本 4 有关联数组,我认为这正是您正在寻找的。

请注意,您需要大量嘈杂的语法(大括号、方括号和引号)才能在 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 智慧的源泉。

关于linux - 在 bash 中迭代数据文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31679738/

相关文章:

linux - Bash 脚本 Shell 脚本

linux - 访问perl中的默认目录

linux - 使用变量写入文件的特定行号

linux - 使用 shell 脚本 ssh 到不同的节点

linux - 如何从 bash 脚本修改/etc/environment

linux - OpenOffice.org 模板在 Linux 中的位置是什么?

bash - 防止引号在 Azure DevOps 任务之间从 JSON 中消失

linux - 连接 linux 程序输出,并只返回那些重复的

bash,获取文件句柄的 mime 类型

bash - 如何让 ack 忽略目录中的文件?