我是新手,不熟悉。我正在尝试移动一个文件,其中数据由空格和“,”分隔,并将信息存储到列表中。唯一的容器bash似乎是一个数组。对此有任何帮助表示赞赏。
假设我有一个名为sample.txt的文件,其中包含用户名密码和出生率,并希望迭代并将用户,密码和生日存储在单独的列表中,这将是实现此目的的最简单方法
sample.txt
user1, password1, 081192
user2, password2, 092578
user3, password3, 020564
答案 0 :(得分:2)
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智慧的源泉。
答案 1 :(得分:0)
你可以像这样使用纯粹的bashisms:
# read a csv line by line and fill an array
# called "myArray" with values from somefile.csv
while IFS=$',' read -r -a myArray; do
echo "${myArray[0]}"
echo "${myArray[1]}"
echo "${myArray[2]}"
done < somefile.csv
示例输出:
foo
bar
baz
tum
di
dum
示例somefile.csv:
foo,bar,baz
tum,di,dum