2016-05-20 28 views
-1

我是新來的shell命令。 我需要做一些高級的搜索腳本,我不知道該怎麼做。使用grep來查找和寫入特定行的條件

我需要在我的計算機日誌文件中查找包含「str1」而不包含「str2」的行,按日期排序大於或等於某個給定日期,並將結果寫入文件,其中進程在後臺運行。

以更正式的方式,我想這樣做:

new_processwritefrom *登錄* where log_line contain 「STR1」 & & log_line not contain 「STR2」 order byDatehaving Date> =%日期%)to讀.txt)

謝謝!

回答

1

你可能比它需要更難。 grep 'str1' "$logfile" | grep -v 'str2'將會找到所有包含str1的行,而不是str2。對於給定的日期,您需要touch一個文件,該文件的mod時間設置爲您要測量的日期。然後使用您的列表來提供while read -r fname; do循環並測試[ "$fname" -nt "testfilename" ]並將滿足該條件的文件寫入新文件。

你最終腳本流程將類似於:

newname="${1:-newfile.txt}" 
touch -d "date string" testfilename 
grep "$str1" "$logfile" | grep -v "str2" | while read -r fname; do 
    [ "$fname" -nt "testfilename" ] && printf "%s\n" "$fname" > "$newname" 
done 
rm testfilename ## clean up 

還有其他的方式來處理這一點,但是這是一個相當標準的做法。如果您還有其他問題,請告訴我。