首页 > 解决方案 > 如何添加和排序特定行的文本行?

问题描述

我有 2 个文件:

first.txt 包含:

A
B
C
D
A
B
C
D

second.txt 包含:

1 header
123
456
2 header
123
1 header
123
2 header
123
456

如何将 second.txt 的每个 1 标头 123 到 2 标头 123 添加和排序到 first.txt 的每个 ABCD 中,如下所示:

A
B
C
D
1 header
123
456
2 header
123
A
B
C
D
1 header
123
2 header
123
456

我尝试使用cat first.txt second.txt,但它只输出如下:

A
B
C
D
A
B
C
D
1 header
123
456
2 header
123
1 header
123
2 header
123
456

你们有什么想法吗?
这些是示例问题,真正的问题有数百万行文本行,由于数据集敏感,我只能分享示例问题。

谢谢,

标签: linuxperlawk

解决方案


您能否尝试关注并让我知道这是否对您有帮助。

awk '
FNR==NR{
  if(FNR%4==0 && FNR>1){
     a[++i]=val ORS $0;
     val="";
     next};
  val=val?val ORS $0:$0;
  next
}
count==3{
  print a[++j] ORS val;
  count="";
  val=""}
/header/{
  count++}
{
  val=val?val ORS $0:$0
}
END{
  if(count){
    print a[++j] ORS val}
}' first.txt second.txt

输出如下。

A
B
C
D
1 header
123
456
2 header
123
A
B
C
D
1 header
123
2 header
123
456

说明:现在也添加上述代码的说明。

awk '
FNR==NR{                 ##Checking condition if FNR value is eqaul to NR value which will be TRUE when first Input_file is being read.
  if(FNR%4==0 && FNR>1){ ##Checking condition if line is completly divided by 4 and NOT the first line then do following.
     a[++i]=val ORS $0;  ##Creating an array named a whose index is variable i increasing value and value is variable val value along with new line and current line.
     val="";             ##Nullifying the variable val here.
     next};              ##Using next keyword to skip al next statements here.
  val=val?val ORS $0:$0; ##Creating variable named val whose value is concatenating its own value in it.
  next                   ##Using next keyword to skip all further statements from here now.
}
count==3{                ##Checking condition if variable named count is 3 then do following.
  print a[++j] ORS val;  ##Printing value of array a whose index is variable j with increasing value of 1 in it then ORS and value of variable val here.
  count="";              ##Nullifying the variable count here.
  val=""}                ##Nullifying the variable val here now.
/header/{                ##Checking condition if a line is having string header in it then do following.
  count++}               ##Increasing the value of variable count with 1 here.
{
  val=val?val ORS $0:$0  ##Creating variable named val whose value is concatenating its own values.
}
END{                     ##Starting END section here of awk.
  if(count){             ##Checking condition if variable count value is NOT NULL then do following.
    print a[++j] ORS val}##Printing value of array a whose index is variable j and ORS and then value of variable val here.
}' first.txt second.txt  ##Mentioning Input_file(s) named first.txt and second.txt here.

推荐阅读