簡體   English   中英

grep兩個模式獨立(在不同的行)

[英]grep for two patterns independently (in different lines)

我有一些具有以下結構的目錄:

DAY1/ # Files under this directory should have DAY1 in the name.
|-- Date
|   |-- dir1 # Something wrong here, there are files with DAY2 and files with DAY1.
|   |-- dir2
|   |-- dir3
|   |-- dir4
DAY2/ # Files under this directory should all have DAY2 in the name.
|-- Date
|   |-- dir1
|   |-- dir2 # Something wrong here, there are files with DAY2, and files with DAY1.
|   |-- dir3
|   |-- dir4

在每個dir中有數十萬個名稱包含DAY的文件,例如0.0000.DAY1.01927492 名稱上帶有DAY1文件應僅出現在父目錄DAY1

復制文件時出錯了,所以我現在在一些dir目錄中有DAY1DAY2混合文件。

我寫了一個腳本來查找包含混合文件的文件夾,因此我可以更仔細地查看它們。 我的腳本如下:

for directory in */; do
    if ls $directory | grep -q DAY2 ; then
        if ls $directory | grep -q DAY1; then 
              echo "mixed files in $directory";
        fi ; 
    fi; 
done

這里的問題是我要經歷兩次所有文件,考慮到我只需要查看一次文件就沒有意義了。

什么是更有效的方式實現我想要的?

如果我理解正確,那么你需要遞歸地找到DAY1目錄下的文件,它們的名字中有DAY2 ,類似於DAY2目錄的文件名稱中有DAY1

如果是這樣,對於DAY1目錄:

find DAY1/ -type f -name '*DAY2*'

這將獲得DAY1目錄下名稱中包含DAY2的文件。 同樣適用於DAY2目錄:

find DAY2/ -type f -name '*DAY1*'

兩者都是遞歸操作。


僅獲取目錄名稱:

find DAY1/ -type f -name '*DAY2*' -exec dirname {} +

請注意, $PWD將顯示為.

要獲得唯一性,請將輸出傳遞給sort -u

find DAY1/ -type f -name '*DAY2*' -exec dirname {} + | sort -u

鑒於通過它們一次並經歷兩次之間的差異只是兩個因素之間的差異,改為只通過它們一次的方法可能實際上不是一個勝利,因為新方法可能很容易花費兩倍每個文件長。

所以你肯定想要試驗; 它不一定是你可以自信地推理的東西。

但是,我會說,除了兩次瀏覽文件之外, ls版本還會對文件進行排序 ,這可能具有超過線性的成本(除非它正在進行某種桶式排序)。 消除,通過編寫ls --sort=none ,而不是僅僅ls ,實際上會提高你的算法復雜度,而且幾乎肯定將得到明顯改善。


但是FWIW,這是一個只能通過文件一次的版本,你可以嘗試:

for directory in */; do
  find "$directory" -maxdepth 1 \( -name '*DAY1*' -or -name '*DAY2*' \) -print0 \
  | { saw_day1=
      saw_day2=
      while IFS= read -d '' subdirectory ; do
        if [[ "$subdirectory" == *DAY1* ]] ; then
          saw_day1=1
        fi
        if [[ "$subdirectory" == *DAY2* ]] ; then
          saw_day2=1
        fi
        if [[ "$saw_day1" ]] && [[ "$saw_day2" ]] ; then
          echo "mixed files in $directory"
          break
        fi
      done
    }
done

暫無
暫無

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

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