僅複製檔案和僅包含字串的行,同時保留目錄結構

僅複製檔案和僅包含字串的行,同時保留目錄結構

假設我有一個包含其他目錄和檔案的目錄。我想在每個文件中搜尋一個字串,並僅將匹配的行複製到另一個位置,同時保留目錄結構。

例如,假設我有這個結構

dir
  subdir1
     file1.txt
  subdir2
     file2.txt

file1.txt:

abc

def

file2.txt:

ghi

現在我只想從包含“de”的文件中獲取匹配的行,所以我想要的結果應該如下所示:

dir
  subdir1
     file1.txt
  subdir2

file1.txt

def

答案1

對於 GNU find(1)xargs(1)、 和grep(1)

  • 複製目錄結構:

    src=/path/to/source
    dest=/other/path/to/destination
    pat='some_grep_pattern'
    
    cd "$dest"
    find "$src" -type d ! -path "$src" -printf '%P\0' | xargs -0 mkdir -p
    
  • 複製具有給定模式的文件:

    cd "$src"
    grep -rlZ "$pat" | \
        (cd "$dest"; \
        xargs -0 sh -c ' \
            while [ $# -ne 0 ]; do \
                grep "$pat" "$src/$1" >"$1"; \
                touch -r "$src/$1" >"$1"; \
                shift; \
            done' sh)
    
  • 恢復權限,假設 Linux,並假設您沒有嵌入換行符的檔案名稱:

    cd "$src"
    getfacl -RPe . | (cd "$dest"; setfacl --restore=-)
    

相關內容