linux - 如何添加和排序特定行的文本行?
问题描述
我有 2 个文件:
- 第一个.txt
- 第二个.txt
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
你们有什么想法吗?
这些是示例问题,真正的问题有数百万行文本行,由于数据集敏感,我只能分享示例问题。
谢谢,
我
解决方案
您能否尝试关注并让我知道这是否对您有帮助。
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.
推荐阅读
- python-3.x - 如果用户在 python3 中没有响应,如何跳过输入语句?
- sql - 我们如何从按 OrderDesc 过滤的子查询中选择所有 CustomerNum?
- laravel - 使用所有可能的值 + 额外列填充数据透视表
- maven - Swagger Jakarta Maven 插件不考虑 Jackson 属性名称
- python - 如何以更简洁的方式填充 Pandas 数据框?
- powershell - 从 AWS CodeDeploy 部署时,Powershell Start-Process 命令在 Windows EC2 实例中不起作用
- html - 如何摆脱 Material UI 复选框周围的空间?
- swiftui - 带有 .listRowInsets(EdgeInsets()) 的披露指标
- python - 类指针的正确类型提示是什么?
- regex - 正则表达式(VS Code)查找和替换子字符串