Cla*_*ied 9 regex bash awk sed pattern-matching
如何在bash中相互同步读取/处理2个文件?
我有2个文本文件,其中包含相同数量的行/项.一个文件是
a
b
c
Run Code Online (Sandbox Code Playgroud)
另一个文件是
1
2
3
Run Code Online (Sandbox Code Playgroud)
如何同步循环这些文件,以便a与1b-> 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
Run Code Online (Sandbox Code Playgroud)
jay*_*ngh 17
您可以使用文件描述符:
while read -r var_from_file1 && read -r var_from_file2 <&3; do
echo "$var_from_file1 ---> $var_from_file2"
done <file1 3<file2
Run Code Online (Sandbox Code Playgroud)
a ---> 1
b ---> 2
c ---> 3
Run Code Online (Sandbox Code Playgroud)
chi*_*rlu 10
使用paste(调用)组合文件,然后一次处理组合文件的一行:
paste file1 file2 |
while read -r first second
do
echo $first
echo $second
done
Run Code Online (Sandbox Code Playgroud)