2015-06-16 216 views
-2

我們有一個包含少量元素列表的文件,每個元素都必須在包含多個文件夾和子文件夾和文件的目錄中進行檢查。 如果我們找到特殊元素,我們應該填充它一個文件,如果它不存在,它必須填充到其他文件...我們如何使用unix shell腳本來做到這一點? 例如:文件1: 一個 乙 Ç d 如果發現elemnt A/B/C /在它應該在一個名爲 「present.txt」 其他在 「Absent.txt」 一個文件被填充任何文件d。 在此之前感謝Shell腳本UNIX

回答

0

這不是一個代碼寫作服務,但沒有什麼比這更好的了,我無論如何都去爲你做了,但老實說,除非自己試着寫,否則你不會學到很多東西。

如果元素文件中每行有一個文件名,或者每行有幾個文件名,那麼您沒有明確說明。我的測試輸入文件gash.txt包含以下內容:

A B C D 
E F G H 
I J K L 

如果每行有一個,那麼腳本會更簡單。那就是:

#!/bin/sh 

# Initialise filenames 
elements=gash.txt 
directory=gash 
present=present.txt 
absent=absent.txt 

# Note that when these are used I enclose them in "quotes" 
# This is to guard against embedded spaces in the names 

# Zeroise files 
> "$present" 
> "$absent" 

# If you have command-line arguments then save them here 
# because I am about to blow them away with the 'set' 

# 'read' reads each line into variable 'REPLY' by default 
while read 
do 
    # This 'set' trick will overwrite the program parameters 
    # It will NOT work if the names in $elements have embedded whitespace 
    set $REPLY 

    # This loops through the command-line arguments by default 
    for fname 
    do 
     # if you don't know the 'find' command then look at 'man find' 
     # Note that 'find' returns 0 even if it didn't find the file 
     result=$(find "$directory" -name "$fname") 

     # The '-n' test returns true if $result is not empty 
     if [[ -n $result ]] 
     then 
      echo "$fname found" 
      echo "$fname" >> "$present" 
     else 
      echo "$fname not found" 
      echo "$fname" >> "$absent" 
     fi 

    done 

done < "$elements" 

一個更復雜的版本將構建從文件名的模式,並使用只需一個電話到「查找」進行搜索,但生命太短暫對於(可能是好項目後) 。

隨時提問!