如何在不创建临时文件的情况下在命令行上加入文件?

dgg*_*dst 7 linux bash shell command-line

我在 Linux/Bash 环境中有两个文件:

# Example data
$ cat abc
2       a
1       b
3       c

$ cat bcd
5       c
2       b
1       d
Run Code Online (Sandbox Code Playgroud)

我正在尝试加入第一列上的两个文件。以下不起作用,因为输入文件必须在匹配字段上排序。

# Wrong: join on unsorted input does not work
$ join abc bcd
Run Code Online (Sandbox Code Playgroud)

我可以通过创建两个临时文件并加入它们来解决这个问题

$ sort abc > temp1
$ sort bcd > temp2
$ join temp1 temp2
1 b d
2 a b
Run Code Online (Sandbox Code Playgroud)

但是有没有办法在不创建临时文件的情况下做到这一点?

dgg*_*dst 18

以下将在 bash shell 中工作:

# Join two files
$ join <(sort abc) <(sort bcd)
1 b d
2 a b
Run Code Online (Sandbox Code Playgroud)

只要您对该列上的输入文件进行排序,就可以加入任何列

# Join on the second field
$ join -j2 <(sort -k2 abc) <(sort -k2 bcd)
b 1 2
c 3 5
Run Code Online (Sandbox Code Playgroud)

sort 的 -k2 参数意味着对第二列进行排序。join 的 -j2 参数意味着在第二列上加入。或者 join -1 x -2 y file1 file2 将在 file1 的 xth 列和 file2 的 yth 列上连接。