我知道要打印文件的行,我可以使用 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[$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
关于linux - 如何根据存储在第三个文件中的行号打印两个文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46550115/