如何在 bash 中同步读取/处理 2 个文件?
我有 2 个文本文件,其中的行数/项目数相同。 一个文件是
a
b
c
另一个文件是
1
2
3
我如何同步循环遍历这些文件,以便 a
与 1
、b->2、c->3 相关联?
我以为我可以将文件作为数组读入,然后用索引处理它们,但似乎我的语法/逻辑不正确。
这样做 f1=$(cat file1)
使得 f1 = a b c
。我认为执行 f1=($(cat file1))
会将其变成一个数组,但它会生成 f1=a
,因此我没有要处理的数组。
万一有人想知道我搞砸的代码是什么:
hostnames=($(cat $host_file))
# trying to read in as an array, which apparently is incorrect
roles=($(cat $role_file))
for i in {0..3}
do
echo ${hostnames[$i]}
# wanted to iterate through each element in the file/array
# but there is only one object instead of N objects
echo ${roles[$i]}
done
最佳答案
您可以使用 file descriptors :
while read -r var_from_file1 && read -r var_from_file2 <&3; do
echo "$var_from_file1 ---> $var_from_file2"
done <file1 3<file2
输出:
a ---> 1
b ---> 2
c ---> 3
关于regex - 如何从两个文件中读取内容并合并到 bash shell 中的第三个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17243235/