使用正则表达式模式使用 sed/awk 从文件中删除多行

pfu*_*her 1 regex awk sed

Eclipse 的“Generate Entities from Tables...”JPA 代码生成器坚持创建@Id 字段和关联的getter/setter 方法,尽管这些是在我在向导步骤中指定的超类中定义的。

为了解决这个问题,我的想法是编写一个脚本来删除违规行并以其他方式清理生成的文件。(是的,我可以使用 Eclipse 中的“查找/替换”对话框手动执行此操作,但我想自动化整个更改集,因为我将在处理各种模型时多次执行此代码生成/清理例程。)

问题是我找不到正确的正则表达式模式来匹配在 awk 或 sed 中使用的多行。我创建的正则表达式模式适用于 Eclipse 和 TextWrangler 的搜索对话框,但不适用于 awk 或 sed。

以下是我想删除的多行文本(当然,在对 awk/sed 的单独调用中):

    @Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(unique=true, nullable=false)
private String id;
Run Code Online (Sandbox Code Playgroud)

    public String getId() {
    return this.id;
}

public void setId(String id) {
    this.id = id;
}
Run Code Online (Sandbox Code Playgroud)

请注意,上面引用的代码中的每个非空行都以 \t 字符开头,即使粘贴到此处时它不存在。

例如,要删除 getter/setter 行,我尝试过

awk '!/\tpublic String getId\(\) \{\r\t\treturn this\.id;\r\t\}\r\r\tpublic void setId\(String id\) \{\r\t\tthis\.id = id;\r\t\}\r/' $file > temp.txt && mv temp.txt $file
Run Code Online (Sandbox Code Playgroud)

或缩短版本

awk '!/^\tpublic String getId.*\r.*\r.*\r\r.*\r.*\r.*\r\r/' ... 
Run Code Online (Sandbox Code Playgroud)

但都不起作用。

(这两种模式都可以在 Eclipse 或 TextWrangler 中找到要删除的行。)

例如,我只能得到单行删除

awk '!/^\tpublic String getId.*\r/' ...
Run Code Online (Sandbox Code Playgroud)

但这没有帮助,因为删除 "\t}\r" 会删除所有方法结束和类结束的花括号。

我在运行 OS X 10.8.2 的 Mac 上这样做,如果这有什么不同的话。

谢谢。

And*_*ndy 5

默认情况下,awk 和 sed 是基于行的工具,因此您不能匹配多于一行。

我建议使用第一行的正则表达式和最后一行的偏移量来确定范围,如下所示:

sed -e '/^\tpublic String getId/,+2 d'
Run Code Online (Sandbox Code Playgroud)

这将删除 linepublic String getId和以下两行。