如何根据存储在第三个文件中的行号打印两个文件中的行

How to print lines from two file according to lines numbers stored in a third file

我知道要打印文件的行,我可以使用 cat、tail、head 或 grep 等。但我的问题对我来说有点复杂。我想不通。

我有两个文件,如果行号存在于第三个文件中,我想并排打印这两个文件中的行。

例如,假设我的前两个文件如下:

文件A:

FileA first sentence
FileA second sentence
FileA third sentence

文件 B:

FileB BBfirst sentence
FileB BBsecond sentence
FileB BBthird sentence

让文件C如下:

文件 C:

    3
    1

所以,我想打印如下:

   FileA third sentence     FileB BBthird sentence
    FileA first sentence    FileB BBfirst sentence

我该怎么做?

awk 拯救:

解决方案 1: 我在 File_C 中获取数字的最高值,然后从 filea 和 fileb 将值存储到数组中,最后遍历该数组.

awk 'FNR==NR{a[[=10=]];len=len>[=10=]?len:[=10=];next} (FNR in a){array[FNR]=array[FNR]?array[FNR] OFS [=10=]:[=10=]} END{for(j=1;j<=len;j++){if(array[j]){print array[j]}}}' fileC  fileA fileB

现在也添加了一种非线性形式的解决方案。

awk '
FNR==NR{
  a[[=11=]];
  len=len>[=11=]?len:[=11=];
  next
}
(FNR in a){
  array[FNR]=array[FNR]?array[FNR] OFS [=11=]:[=11=]
}
END{
  for(j=1;j<=len;j++){
    if(array[j]){
      print array[j]
}
}
}
' fileC  fileA fileB

输出如下。

FileA first sentence FileB BBfirst sentence
FileA third sentence FileB BBthird sentence

解决方案 2: 这里我没有使用 filec 中的任何最大数字概念,只是根据元素的出现将元素保存到数组中,并在第一行出现时重置变量的值filea 和 fileb 这样我们就可以节省一些 for 循环的循环(这在我的第一个解决方案中是做不到的)。

awk '
FNR==NR{
 a[[=13=]];
 next
}
FNR==1{
 i=""
}
(FNR in a){
 ++i;
 array[i]=array[i]?array[i] OFS [=13=]:[=13=]
}
END{
 for(j=1;j<=i;j++){
  if(array[j]){
    print array[j]
}
}
}
' file_c  file_a file_b

输出如下。

FileA first sentence FileB BBfirst sentence
FileA third sentence FileB BBthird sentence