如何使用sed命令删除具有特定文本的行?

时间:2021-08-06 02:22:37

I saw a similar Question on this forum but this question is little different from those questions. Hence please do not consider this as a duplicate.

我在这个论坛上看到了一个类似的问题,但这个问题与这些问题没什么不同。因此,请不要认为这是副本。

I have a file containing data as

我有一个包含as数据的文件

blah blah
blah blah Select from table blah blah QWERTY blah
Select from table
QWERTY Here
blah blah

Now I want to delete all the lines having both Select from table and QWERTY

现在我要删除所有从表和QWERTY中选择的行

Expected Output:

预期的输出:

blah blah
Select from table
QWERTY Here
blah blah

I tried as below:

我尝试了如下:

sed /*Select from table*QWERTY*/d file.txt

But it is not working. Could anyone please help on this?

但这并不奏效。有人能帮忙吗?

1 个解决方案

#1


3  

You was close with you sed attempt:

你和你的尝试很接近:

$ sed '/Select from table.*QWERTY/d' file
blah blah
Select from table
QWERTY Here
blah blah

You should always quotes the script with single quotes and don't confuse shell globbing with regular expressions. To match zero or more of any character using regular expressions is .*.

您应该始终使用单引号引用脚本,不要将shell globbing与正则表达式混淆。使用正则表达式匹配任何字符的零个或多个是。*。


If order is guaranteed then a simply grep will do using the -v option:

如果订单得到保证,那么一个简单的grep将使用-v选项:

$ grep -v 'Select from table.*QWERTY' file
blah blah
Select from table
QWERTY Here
blah blah

If order isn't guaranteed then used a language such as awk where you can combine regular expression matches with logical operators:

如果顺序没有保证,那么使用一种语言,比如awk,您可以将正则表达式匹配与逻辑运算符组合在一起:

$ awk '!/Select from table/||!/QWERTY/' file
blah blah
Select from table
QWERTY Here
blah blah

#1


3  

You was close with you sed attempt:

你和你的尝试很接近:

$ sed '/Select from table.*QWERTY/d' file
blah blah
Select from table
QWERTY Here
blah blah

You should always quotes the script with single quotes and don't confuse shell globbing with regular expressions. To match zero or more of any character using regular expressions is .*.

您应该始终使用单引号引用脚本,不要将shell globbing与正则表达式混淆。使用正则表达式匹配任何字符的零个或多个是。*。


If order is guaranteed then a simply grep will do using the -v option:

如果订单得到保证,那么一个简单的grep将使用-v选项:

$ grep -v 'Select from table.*QWERTY' file
blah blah
Select from table
QWERTY Here
blah blah

If order isn't guaranteed then used a language such as awk where you can combine regular expression matches with logical operators:

如果顺序没有保证,那么使用一种语言,比如awk,您可以将正则表达式匹配与逻辑运算符组合在一起:

$ awk '!/Select from table/||!/QWERTY/' file
blah blah
Select from table
QWERTY Here
blah blah