2017-02-22 70 views
-3

说我有以下文件中最后一次出现之前:桑达:追加角色

public class Foo { 
    // Some code 
    // There will be functions here, so there are other {} 

    // I WANT TO INSERT HERE 
} 

我想插入Foo类中的功能。这将在最后一次出现}之前。

我该如何在sed中做到这一点?

编辑

怎么样在Mac和Linux上工作的脚本?

+0

是否有多个}?如果没有用$ Yourstuff}替换}像这样sed“s /}/$ yourstuff} /” –

+0

@MikeWodarczyk,是的,会有更多的'}' – Kousha

+1

有多个'}'没有前面的空白吗? – choroba

回答

0
sed '$s/\(}\)/Put thing here\n\1/' 

$前最后一行匹配的直线距离,因此,如果}不是在文件的最后一行,它不会工作。

+0

如果必须,请随时downvote。我已经指定了我的sed什么时候会工作。在这个问题上,我没有看到足够的信息是否在最后一行,所以只需简单地回答一个简单的情况。 – Munir

+0

Nah我不能这么做,我不是在批评你的努力,只是OS X上的行为将字符串放在{}之前}。 –

+0

对不起......我不知道。我用GNU sed在linux上测试了这个。 – Munir

0

假设不是单一类的更多和其他可能的文件中的数据:

sed '/Foo/,/^}/s%^}%\t//New insert\n}%' file 

在这一天结束时,你总是可以找到的东西,将与您的解决方案不太用,所以你可能需要要知道你的数据:)

下面还将与类定义应对所有在同一行:

sed -e '/Foo/,/^}/s%^}%\t//New insert\n}%' -e '/Foo.*}$/s%}$%\t //New insert\n}%' file 
+0

如果这个类全部都是一行(例如'class {... {}}',这不起作用......在一些版本的sed中,\ t'或'\ n'将会结束打印只需“t”或“n”而不是制表符/新行。 –

0

这确实与GNU桑达4.2.2工作在RedHat的(你可以测试它here如果你喜欢)

$ sed -n '/class Foo2 {/,/^}$/{s/^}$/Insert here\n\0/};p' file 

我认为该文件可能包含更多的类,我尝试插入类foo2的在文件中结束之前我的文字(此处插入)。

测试:

$ cat file2 
public class Foo { 
    // Some code 
    // There will be functions here, so there are other {} 
} 
public class Foo2 { 
    // Some code 
    // There will be functions here, so there are other {} 
} 
public class Foo3 { 
    // Some code 
    // There will be functions here, so there are other {} 
} 


$ sed -n '/class Foo2 {/,/^}$/{s/^}$/Insert here\n\0/};p' file2 
public class Foo { 
    // Some code 
    // There will be functions here, so there are other {} 
} 
public class Foo2 { 
    // Some code 
    // There will be functions here, so there are other {} 
Insert here 
} 
public class Foo3 { 
    // Some code 
    // There will be functions here, so there are other {} 
} 

说明:
/class Foo2 {//^}$/ - 范围 - 从class name Foo2 {到第一^}$
{s/^}$/Insert here\n\0/} - 替换部分。与your textnew line更换^}$加上替换部分\0
;p:打印

更新BSD
随着@ghoti和配置一台FreeBSD机器进行测试后,神奇的帮助下,这似乎在FreeBSD上运行( bash):

sed -n "/class Foo2 {/,/^}\$/{s/^}\$/Insert here \\"$'\n'" &/;};p" file 

请注意,如果shell不是bash,这是行不通的。无论如何,你可以试试。

+0

@ kousha是否为您工作? –

+0

这在Linux上工作,而不是在Mac上:( – Kousha

+0

@Kousha Hm ...不好,我也试过用sed --posix,工作的很好,你用什么sed版本? –

1

试试这个:

sed -i '/^\(}\)/ i new_function' file 

他的工作是我在Debian。