如何使用grep检查模式行是否存在并写入另一个文件?

问题描述 投票:0回答:1

我的日志文件内容如下

The color is Orange then can used to binding.
The color is Black then can used to binding.
The animal Lion need to carefully. 
The color is Black then can used to binding.
The animal Zebra need to carefully. 
The animal Tiger need to carefully.
The animal Bee need to skip.
The color is White then can used to binding.
The color is Yellow then can used to binding.
The animal Ant need to skip.
The animal Tiger need to carefully. 
The color is Red then can used to filled.
The color is Green then can used to filled.

我想检查行是否包含模式且不存在,然后写入另一个日志。

#!/bin/bash
source_file="/home/user1/source/source_sample.log"
dest_file="/home/user1/dest/dest_sample.log

#define line with pattern
pattern1=".*then can used to binding"
pattern2=".*need to carefully"

#check if line of pattern exits or not in destination file, if not then write it
grep -e "$pattern1" -e "$pattern2" $source_file >> $dest_file

dest_sample.log 上的预期输出将是这样的

The color is Orange then can used to binding.
The color is Black then can used to binding.
The animal Lion need to carefully. 
The animal Zebra need to carefully. 
The animal Tiger need to carefully.
The color is White then can used to binding.
The color is Yellow then can used to binding.
linux bash shell unix sh
1个回答
0
投票

一个简单的egrep命令就可以了:

$ egrep '(then can used to binding|need to carefully)' input.txt
The color is Orange then can used to binding.
The color is Black then can used to binding.
The animal Lion need to carefully.
The color is Black then can used to binding.
The animal Zebra need to carefully.
The animal Tiger need to carefully.
The color is White then can used to binding.
The color is Yellow then can used to binding.
The animal Tiger need to carefully.
© www.soinside.com 2019 - 2024. All rights reserved.