Bash

find、xargs 和 egrep 的問題

  • January 8, 2017

我這就是我想要得到的結果(除了工作)

find ./ -mindepth 1 -type f -mtime +60 -print0 | xargs -0 egrep -vZ 'vvv|iii'

我究竟做錯了什麼?

$ ll
total 0
-rw-rw-r-- 1 yyy yyy 0 Sep 18 10:36 iii.txt
-rw-rw-r-- 1 yyy yyy 0 Aug 29 10:35 old1.txt
-rw-rw-r-- 1 yyy yyy 0 Aug 29 10:35 old2.txt
-rw-rw-r-- 1 yyy yyy 0 Aug 29 10:35 old3.txt
-rw-rw-r-- 1 yyy yyy 0 Nov 16 09:36 vvv.txt
-rw-rw-r-- 1 yyy yyy 0 Nov  5 09:41 young.txt 
$    find ./ -mindepth 1 -type f -mtime +60 -print0 | xargs -0 egrep -viZ 'vvv|iii'
$    find ./ -mindepth 1 -type f -mtime +60 -print0 | xargs -0 egrep -vilZ 'vvv|iii'
$    find ./ -mindepth 1 -type f -mtime +60 -print0 
./old3.txt./old1.txt./old2.txt$    find ./ -mindepth 1 -type f -mtime +60 -print0 | xargs -0 egrep 'old'
$    find ./ -mindepth 1 -type f -mtime +60 -print0 | xargs -0 grep 'old'
$    find ./ -mindepth 1 -type f -mtime +60 -print0 | xargs -0 grep 'o'
$    find ./ -mindepth 1 -type f -mtime +60 -print0 | xargs -0 grep '.*o.*' 
$    find ./ -mindepth 1 -type f -mtime +60 | xargs egrep 'o'
$    find ./ -mindepth 1 -type f -mtime +60 | xargs egrep '.*o.*'
$    find ./ -mindepth 1 -type f -mtime +60
./old3.txt
./old1.txt
./old2.txt
$    find ./ -mindepth 1 -type f -mtime +60 | grep 'o'
./old3.txt
./old1.txt
./old2.txt
$    find ./ -mindepth 1 -type f -mtime +60 | xargs grep 'o'
$    find ./ -mindepth 1 -type f -mtime +60 -print | xargs grep 'o'
$    find . -name "*.txt" | xargs grep "old"
$    find . -name "*.txt"
./old3.txt
./vvv.txt
./iii.txt
./old1.txt
./old2.txt
./young.txt
$ find ./ | grep 'o'
./old3.txt
./old1.txt
./old2.txt
./young.txt
$ find ./ | xargs grep 'o'
$

我需要 grep,因為排除列表最終將來自一個文件,因此僅使用 find 進行過濾是不夠的。我也希望 grep 返回一個NUL終止的列表。之後我將把這個結果傳遞給其他東西,所以我不知道 find 選項-exec是否合適。

我看過的東西:

$ bash -version
GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
$ cat /proc/version
Linux version 2.6.18-371.8.1.0.1.el5 (mockbuild@ca-build56.us.oracle.com) (gcc version 4.1.2 20080704 (Red Hat 4.1.2-54)) #1 SMP Thu Apr 24 13:43:12 PDT 2014

免責聲明:我沒有很多 linux 或 shell 經驗。

看起來你想grep在文件名上,如果你這樣做的話:

find ./ -mindepth 1 -type f -mtime +60 -print0 | xargs -0 egrep -vZ 'vvv|iii'

實際上顯示了作為參數xargs出來的文件列表。find``egrep

你應該做什麼來處理 NUL 終止的輸入(來自-print0

find ./ -mindepth 1 -type f -mtime +60 -print0 | xargs -0 grep -EvzZ 'vvv|iii'

egrep已棄用,這就是我將其更改為的原因grep -E

來自man grep

  -z, --null-data
         Treat the input as a set of lines, each  terminated  by  a  zero
         byte  (the  ASCII NUL character) instead of a newline.  Like the
         -Z or --null option, this option can be used with commands  like
         sort -z to process arbitrary file names.

  -Z, --null
         Output  a  zero  byte  (the  ASCII NUL character) instead of the
         character that normally follows a file name. 

所以你需要-z兩者-Z

引用自:https://unix.stackexchange.com/questions/168451