簡體   English   中英

如何使用bash comm獲取A目錄中的文件而不是B目錄中的文件,反之亦然?

[英]How to get files in directory A but not B and vice versa using bash comm?

我正在嘗試使用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

第一個目錄的名稱中有一個選項卡,因此所有條目都被認為是不同的。 我究竟做錯了什么?

comm根據輸入標志生成 1 到 3 列輸出; 輸出的第二列將有一個前導選項卡,而輸出的第三列將有 2 個前導選項卡。

在這種情況下,OP 的代碼表示忽略第 3 列( -3 ,2 個源之間共有的文件),因此comm生成 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 before 'b.txt' (3rd column), 1x tab 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 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

如果basename導致問題,您可以使用 find 的 printf :

#!/bin/bash
    
find_basename(){
    find "$1" -type f -printf "%P\n" | sort
}

comm -3 <(find_basename /Users/rob/A) <(find_basename /Users/rob/B)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM