2013-11-26 74 views
1

我想搜索文件中的圖案並刪除包含圖案的線條。要做到這一點,正在使用:刪除與圖案匹配的線條

originalLogFile='sample.log' 
outputFile='3.txt' 
temp=$originalLogFile 

while read line 
do 
    echo "Removing" 
    echo $line 
    grep -v "$line" $temp > $outputFile 
    temp=$outputFile 
done <$whiteListOfErrors 

這適用於第一次迭代。對於第二輪,它拋出:

grep: input file ‘3.txt’ is also the output 

任何解決方案或替代方法?

回答

3

下應相當於

grep -v -f "$whiteListOfErrors" "$originalLogFile" > "$outputFile" 
0
originalLogFile='sample.log' 
outputFile='3.txt' 
tmpfile='tmp.txt' 
temp=$originalLogFile 
while read line 
do 
    echo "Removing" 
    echo $line 
    grep -v "$line" $temp > $outputFile 
    cp $outputfile $tmpfile 
    temp=$tmpfile 
done <$whiteListOfErrors 
0

這種用途sed

sed '/.*pattern.*/d' file 

如果你有多個模式,你可以使用-e選項

sed -e '/.*pattern1.*/d' -e '/.*pattern2.*/d' file 

如果你有GNU sed(Linux上的典型值)的-i選項因爲它可以修改原始文件而不是寫入新文件。 (但是小心處理,以不覆蓋原始)

+0

前緣和後''是多餘的。無論如何,請與@ 1_CR的答案。 – tripleee

+0

耶'grep'在這裏更好 – hek2mgl

+0

而且,像這樣使用'sed'不能很好地處理多種模式。 – user2719058

-1

平凡的解決方案可能是交替的文件工作;例如

idx=0 
while ... 
    let next='(idx+1) % 2' 
    grep ... $file.$idx > $file.$next 
    idx=$next 

更優雅可能是一個大的grep命令

args=() 
while read line; do args=("${args[@]}" -v "$line"); done < $whiteList 
grep "${args[@]}" $origFile 
0

用它來解決問題的創造:

while read line 
do 
    echo "Removing" 
    echo $line 
    grep -v "$line" $temp | tee $outputFile 
    temp=$outputFile 
done <$falseFailures