awk命令用于将两个以冒号分隔的文件合并,类似以下输出:

huangapple go评论61阅读模式
英文:

awk command for combine two file with separate ':' like output

问题

请帮我使用awk命令处理这个输出,使用文件1和文件2作为输入,并以冒号作为分隔符。输出如下:

1:23
1:45
1:27
1:67
1:867
2:23
2:45
2:27
2:67
2:867
3:23
3:45
3:27
3:67
3:867
英文:

please help me with awk

file 1

1
2
3

file 2

23
45
27
67
867

output

1:23
1:45
1:27
1:67
1:867
2:23
2:45
2:27
2:67
2:867
3:23
3:45
3:27
3:67
3:867

please help me how to command this output using awk using delimeter ':' from file 1 and file 2 like output

答案1

得分: 1

有很多方法可以解决您的问题;这个方法适合您的用例吗?

awk 'NR==FNR{a[++n]=$0; next} {for (i=1; i<=n; i++) {print $0 ":" a[i]}}' file2 file1
1:23
1:45
1:27
1:67
1:867
2:23
2:45
2:27
2:67
2:867
3:23
3:45
3:27
3:67
3:867

带有更好的格式和注释的版本:

awk '
NR==FNR{                                # 对于第一个文件
       a[++n]=$0                         # 将值加载到数组中
       next                             # 然后跳到下一行/文件
}

{
       for (i=1; i<=n; i++) {   # 对数组中的所有项目
              print $0 ":" a[i]         # 打印来自file1的值,然后是数组中的值
       }
}' file2 file1
1:23
1:45
1:27
1:67
1:867
2:23
2:45
2:27
2:67
2:867
3:23
3:45
3:27
3:67
3:867

或者,也许可以使用GNU parallel:

parallel echo {1}:{2} :::: file1 :::: file2
1:23
1:45
1:27
1:67
1:867
2:23
2:45
2:27
2:67
2:867
3:23
3:45
3:27
3:67
3:867

编辑

如果您的输入中有&lt;br/&gt;字符,您可以使用以下方法删除除数字之外的任何字符:

awk 'NR==FNR{gsub("[^0-9]", "", $0); a[++n]=$0; next} {for (i=1; i<=n; i++) {gsub("[^0-9]", "", $0); print $0 ":" a[i]}}' file2 file1
英文:

There are many ways to solve your problem; would this suit your use-case?

awk &#39;NR==FNR{a[++n]=$0; next} {for (i=1; i&lt;=n; i++) {print $0 &quot;:&quot; a[i]}}&#39; file2 file1
1:23
1:45
1:27
1:67
1:867
2:23
2:45
2:27
2:67
2:867
3:23
3:45
3:27
3:67
3:867

With nicer formatting and comments

awk &#39;
NR==FNR{                                # for the first file
       a[++n]=$0                         # load values into an array
       next                             # then skip to the next line/file
}

{
       for (i=1; i&lt;=n; i++) {   # for all the items in the array
              print $0 &quot;:&quot; a[i]         # print the value from file1, then the value from the array
       }
}&#39; file2 file1
1:23
1:45
1:27
1:67
1:867
2:23
2:45
2:27
2:67
2:867
3:23
3:45
3:27
3:67
3:867

Or, perhaps with GNU parallel:

parallel echo {1}&quot;:&quot;{2} :::: file1 :::: file2
1:23
1:45
1:27
1:67
1:867
2:23
2:45
2:27
2:67
2:867
3:23
3:45
3:27
3:67
3:867

Edit

If you have &lt;br/&gt; characters in your input, you can delete anything that isn't a number using:

awk &#39;NR==FNR{gsub(&quot;[^0-9]&quot;, &quot;&quot;, $0); a[++n]=$0; next} {for (i=1; i&lt;=n; i++) {gsub(&quot;[^0-9]&quot;, &quot;&quot;, $0); print $0 &quot;:&quot; a[i]}}&#39; file2 file1

huangapple
  • 本文由 发表于 2023年6月16日 12:41:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76487005.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定