如果满足不同行上的两个条件,则删除行

时间:2017-09-06 14:15:32

标签: string awk pattern-matching conditional-statements matching

假设多行文本文件file

$cat file
foo bar baz
foo bar baz qux
foo bar baz quux  # Line to be deleted
foo bar quux

我希望删除满足这两个条件的所有行:(a)该行包含关键字“ quux ”,(b)该行立即包含关键字“ qux ”的行。

$cat file | sought_command
foo bar baz
foo bar baz qux
foo bar quux

我不知道哪个UNIX工具可以应用于这样的双重条件(可能是 awk ,但我不确定)并且会很感激建议。

修改1 : 在被告知awk是使用的工具并且在进一步考虑任务时,我正在寻找可以容易地修改的代码,使得条件(b)可以被反转(即,“(b)线如果需要,不会立即在包含关键字“qux”“)的行之前。

3 个答案:

答案 0 :(得分:0)

awk 脚本可以执行您想要的操作:

$ cat tst.awk
/quux/ && p { p=/qux/; next }
{ p=/qux/ }
{ print }

输入:

$ cat input.txt
foo bar baz qux
foo bar baz quux qux
foo bar baz quux
foo bar quux

给出:

$ awk -f tst.awk input.txt
foo bar baz qux
foo bar quux

后续问题是删除一行包含'quux'并且前一行包含'qux'。一个简单的否定p就是要做的事。

 cat tst2.awk
 /quux/ && !p { p=/qux/; next }
 { p=/qux/ }
 { print }

输入:

$ cat del.txt
foo bar baz qux
foo bar baz quux qux
foo bar baz quux
foo bar quux       # to be deleted

给出:

 awk -f tst2.awk del.txt
 foo bar baz qux
 foo bar baz quux qux
 foo bar baz quux

答案 1 :(得分:0)

这可能是您正在寻找的内容,具体取决于您是否需要字符串或正则表达式比较以及部分或完全匹配。

1)删除包含quux的行,前一行包含qux:

$ awk '!(/quux/ && p~/qux/); {p=$0}' file
foo bar baz
foo bar baz qux
foo bar quux

2)如果行包含quux并且前一行不包含qux:

,则删除该行
awk '!(/quux/ && p!~/qux/); {p=$0}' file

如果您希望避免双重否定,则布尔代数可以减少为:

awk '!/quux/ || p~/qux/; {p=$0}' file

您喜欢的任何复合条件都只需通过&& -ing和/或|| -ing和/或否定$ 0上的测试(隐含在/.../)和p。

答案 2 :(得分:0)

您可以通过以下方式使用Map { id: map anchors.fill: parent plugin: mapPlugin center: QtPositioning.coordinate(22.5726, 88.3639) zoomLevel: 14 MapItemView { model: markerModel delegate: markerDelegate } Component { id: markerDelegate MapQuickItem{ anchorPoint: Qt.point(2.5, 2.5) coordinate: QtPositioning.coordinate(position.x, position.y) zoomLevel: 0 sourceItem: Rectangle{ width: settings.marker_size; height: settings.marker_size; radius: settings.marker_size/2; color: settings.marker_colors[status] border.color: "white" border.width: 1 } } } } Rectangle { id: rectangle1 anchors.top: map.top anchors.right: map.right width: 500 height: 750 color: "#ffffff" }

awk
相关问题