读取两个文本文件,连接每一行

读取两个文本文件,连接每一行

我有两个长度相同的文本文件,按顺序排列:一个是产品,另一个是比较产品。我希望每行的输出都是“产品;比较”。是的,我可以将它们放入电子表格中并导出为 csv,但我想了解如何在 bash 中执行此操作。这两个文件作为参数提供。

#!/bin/bash
file1="$1";
file2="$2";
separator=";";
while read -r product
do
  read -r comp < "$file2";
  echo $product $separator $comp >> temp.txt;
done < "$file1"
tr -d " " < temp.txt | sort > out.txt
rm temp.txt

这为我提供了具有相同比较产品的所有产品!例如

$: cat out.txt
product1;comp1
product2;comp1
product3;comp1

我显然没有正确读取 comp 文件的单行 - 我做错了什么?如何读取一行?

答案1

如果你真的想在 bash 中执行此操作,我建议使用-u fd使用编号流同时读取两个文件的选项,例如

while read -r -u3 product; read -r -u4 comp; do 
  printf '%s;%s\n' "$product" "$comp"
done 3<products.txt 4<comps.txt

但是,您可以只使用该paste实用程序

paste -d\; products.txt comps.txt

相关内容