regex - 如何从两个文件中读取内容并合并到 bash shell 中的第三个文件

标签 regex bash awk sed pattern-matching

如何在 bash 中同步读取/处理 2 个文件?

我有 2 个文本文件,其中的行数/项目数相同。 一个文件是

a
b
c

另一个文件是

1
2
3

我如何同步循环遍历这些文件,以便 a1、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/

相关文章:

regex - 从数据框中删除百分比

javascript - 使用数组查找文本并替换为类等于文本的文本周围的链接

regex - 用于翻译一行中以制表符分隔的第三个单词的 Shell 脚本

linux - 编写一个 bash 脚本来比较两个比较时间戳的日志文件

regex - R 中的 LEFT 加 FIND 函数相当于什么?

bash - sed,引号中的正斜杠

bash - 你怎么能强制 bc 遵循比例?

python - 在 python 风格中使用正则表达式来匹配字符串中的一个(或全部)bash 波浪号前缀?

linux - 在Linux中建立文件索引

string - 多个字符串,在 80 个字符处截断行