英文:
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
编辑
如果您的输入中有<br/>
字符,您可以使用以下方法删除除数字之外的任何字符:
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 '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
With nicer formatting and comments
awk '
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<=n; i++) { # for all the items in the array
print $0 ":" a[i] # print the value from file1, then the value from the array
}
}' 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}":"{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 <br/>
characters in your input, you can delete anything that isn't a number using:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论