[英]Removing lines matching a pattern
I want to search for patterns in a file and remove the lines containing the pattern. 我想在文件中搜索模式并删除包含模式的行。 To do this, am using: 为此,我正在使用:
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
This works fine for the first iteration. 对于第一次迭代,这工作正常。 For the second run, it throws : 对于第二次运行,它抛出:
grep: input file ‘3.txt’ is also the output
Any solutions or alternate methods? 任何解决方案或替代方法?
以下应等效
grep -v -f "$whiteListOfErrors" "$originalLogFile" > "$outputFile"
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
Use sed
for this: 为此使用sed
:
sed '/.*pattern.*/d' file
If you have multiple patterns you may use the -e
option 如果您有多个模式,则可以使用-e
选项
sed -e '/.*pattern1.*/d' -e '/.*pattern2.*/d' file
If you have GNU sed
(typical on Linux) the -i
option is comfortable as it can modify the original file instead of writing to a new file. 如果您具有GNU sed
(通常在Linux上),则-i
选项很舒适,因为它可以修改原始文件,而不必写入新文件。 (But handle with care, in order to not overwrite your original) (但是请小心处理,以免覆盖您的原件)
Used this to fix the problem: 用它来解决问题:
while read line
do
echo "Removing"
echo $line
grep -v "$line" $temp | tee $outputFile
temp=$outputFile
done <$falseFailures
Trivial solution might be to work with alternating files; 简单的解决方案可能是使用交替文件。 eg 例如
idx=0
while ...
let next='(idx+1) % 2'
grep ... $file.$idx > $file.$next
idx=$next
A more elegant might be the creation of one large grep
command 一个更优雅的方法可能是创建一个大的grep
命令
args=( )
while read line; do args=( "${args[@]}" -v "$line" ); done < $whiteList
grep "${args[@]}" $origFile
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.