GNU/Linux中两个文件(作为行集)的笛卡尔积 [英] Cartesian product of two files (as sets of lines) in GNU/Linux
本文介绍了GNU/Linux中两个文件(作为行集)的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
与笛卡尔积一样,如何使用外壳一线和通用GNU工具将两个文件中的行连接起来?最简洁,美观和"linuxy"的方式是什么?
How can I use shell one-liners and common GNU tools to concatenate lines in two files as in Cartesian product? What is the most succinct, beautiful and "linuxy" way?
例如,如果我有两个文件:
For example, if I have two files:
$ cat file1
a
b
$ cat file2
c
d
e
结果应该是
a, c
a, d
a, e
b, c
b, d
b, e
推荐答案
在此处执行此操作的shell脚本
Here's shell script to do it
while read a; do while read b; do echo "$a, $b"; done < file2; done < file1
尽管那会很慢. 我想不出任何预编译的逻辑来完成此任务. 速度的下一步将是在awk/perl中执行上述操作.
Though that will be quite slow. I can't think of any precompiled logic to accomplish this. The next step for speed would be to do the above in awk/perl.
awk 'NR==FNR { a[$0]; next } { for (i in a) print i",", $0 }' file1 file2
嗯,这个骇人的解决方案使用预编译的逻辑怎么样?
Hmm, how about this hacky solution to use precompiled logic?
paste -d, <(sed -n "$(yes 'p;' | head -n $(wc -l < file2))" file1) \
<(cat $(yes 'file2' | head -n $(wc -l < file1)))
这篇关于GNU/Linux中两个文件(作为行集)的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文