繁体   English   中英

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

[英]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

文件乙:

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 来拯救:

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

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

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

awk '
FNR==NR{
  a[$0];
  len=len>$0?len:$0;
  next
}
(FNR in a){
  array[FNR]=array[FNR]?array[FNR] OFS $0:$0
}
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[$0];
 next
}
FNR==1{
 i=""
}
(FNR in a){
 ++i;
 array[i]=array[i]?array[i] OFS $0:$0
}
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM