首页 > 解决方案 > 如何使用bash comm获取目录A而不是B中的文件,反之亦然?

问题描述

我正在尝试用于comm获取不在 B 上的文件夹 A 上的文件,反之亦然:

comm -3 <(find /Users/rob/A -type f -exec basename {} ';' | sort) <(find "/Users/rob/B" -type f -exec basename {} ';' | sort)

basename {} ';'用来排除目录路径,但这是我得到的输出:

    IMG_5591.JPG
IMG_5591.jpeg
    IMG_5592.JPG
IMG_5592.jpeg
    IMG_5593.JPG
IMG_5593.jpeg
    IMG_5594.JPG
IMG_5594.jpeg

第一个目录的名称中有一个选项卡,因此所有条目都被认为是不同的。我究竟做错了什么?

标签: bashfindcomm

解决方案


前导选项卡不是find|basename代码生成的;主要标签是由comm...生成的

comm根据输入标志生成 1 到 3 列输出;第 2 列输出将有一个前导选项卡,而第 3 列输出将有 2 个前导选项卡。

在这种情况下,OP 的代码说忽略第 3 列(-32 个源之间共有的文件),因此comm生成 2 列输出,其中第 2 列具有前导选项卡。

一个简单的解决方法:

comm --output-delimiter="" <(find...|sort...) <(find...|sort...)

如果由于某种原因您comm不支持该--output-delimiter标志:

comm <(find...|sort...) <(find...|sort...) | tr -d '\t'

这假设文件名不包含嵌入的选项卡,否则将替换为tr您喜欢的代码以去除前导空格,例如:

comm <(find...|sort...) <(find...|sort...) | sed 's/^[[:space:]]*//'

演示...

$ cat file1
a.txt
b.txt

$ cat file2
b.txt
c.txt

$ comm file1 file2
a.txt
                b.txt
        c.txt

# 2x tabs (\t) before 'b.txt' (3rd column), 1x tab (\t) before 'c.txt' (2nd column):

$ comm file1 file2 | od -c
0000000   a   .   t   x   t  \n  \t  \t   b   .   t   x   t  \n  \t   c
0000020   .   t   x   t  \n

# OP's scenario:

$ comm -3 file1 file2
a.txt
        c.txt

# 1x tab (\t) before 'c.txt' (2nd column):

$ comm -3 file1 file2 | od -c
0000000   a   .   t   x   t  \n  \t   c   .   t   x   t  \n

删除前导选项卡:

$ comm --output-delimiter="" -3 file1 file2
a.txt
c.txt

$ comm -3 file1 file2 | tr -d '\t'
a.txt
c.txt

$ comm -3 file1 file2 | sed 's/^[[:space:]]*//'
a.txt
c.txt

推荐阅读