在bash中如何读取/处理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
你的方式:
- host_file=host1
- role_file=role1
- hostnames=( $(cat $host_file) )
- roles=( $(cat $role_file) )
- (( cnt = ${#hostnames[@]} -1 ))
- echo "cnt is $cnt"
- for (( i=0;i<=$cnt;i++))
- do
- echo "${hostnames[$i]} -> ${roles[$i]}"
- done