用不同的IFS解析文本文件

时间:2013-02-13 19:20:51

标签: arrays bash parsing

这是我文件txt中的情况:

kevin \t password \t path \n

steve \t password \t path \n

etc...

如何解析这种文件以将名称转换为数组,将密码转换为另一个数组并将路径转换为idem? 我想使用IFS变量,但我有问题确定什么是id或psw或路径。

我从这段代码开始:

old_IFS=$IFS

IFS=$'\t\n'

lines=($(cat MYFILE)) 

IFS=$old_IFS

或者最好使用awk?

有人有想法吗?

2 个答案:

答案 0 :(得分:1)

使用while read循环:

while IFS=$'\t' read user password path
do
    users+=( "$user" )
    passwords+=( "$password" )
    paths+=( "$path" )
    echo "$user's password is $password, and their path is $path"
done < yourtextfile

答案 1 :(得分:0)

这是一种低效的方法,但很容易阅读:

f() {
    local IFS=$'\n' # Don't wordsplit on just any whitespace. Newlines only
    names=( $(cut -d$'\t' -f1 < file) )
    passes=( $(cut -d$'\t' -f2 < file) )
    paths=( $(cut -d$'\t' -f3 < file) )
}
f