说我有以下文件中最后一次出现之前:桑达:追加角色
public class Foo {
// Some code
// There will be functions here, so there are other {}
// I WANT TO INSERT HERE
}
我想插入Foo
类中的功能。这将在最后一次出现}
之前。
我该如何在sed中做到这一点?
编辑
怎么样在Mac和Linux上工作的脚本?
说我有以下文件中最后一次出现之前:桑达:追加角色
public class Foo {
// Some code
// There will be functions here, so there are other {}
// I WANT TO INSERT HERE
}
我想插入Foo
类中的功能。这将在最后一次出现}
之前。
我该如何在sed中做到这一点?
编辑
怎么样在Mac和Linux上工作的脚本?
假设不是单一类的更多和其他可能的文件中的数据:
sed '/Foo/,/^}/s%^}%\t//New insert\n}%' file
在这一天结束时,你总是可以找到的东西,将与您的解决方案不太用,所以你可能需要要知道你的数据:)
下面还将与类定义应对所有在同一行:
sed -e '/Foo/,/^}/s%^}%\t//New insert\n}%' -e '/Foo.*}$/s%}$%\t //New insert\n}%' file
如果这个类全部都是一行(例如'class {... {}}',这不起作用......在一些版本的sed中,\ t'或'\ n'将会结束打印只需“t”或“n”而不是制表符/新行。 –
这确实与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 text
加new line
更换^}$
加上替换部分\0
;p
:打印
更新BSD
随着@ghoti和配置一台FreeBSD机器进行测试后,神奇的帮助下,这似乎在FreeBSD上运行( bash):
sed -n "/class Foo2 {/,/^}\$/{s/^}\$/Insert here \\"$'\n'" &/;};p" file
请注意,如果shell不是bash,这是行不通的。无论如何,你可以试试。
@ kousha是否为您工作? –
这在Linux上工作,而不是在Mac上:( – Kousha
@Kousha Hm ...不好,我也试过用sed --posix,工作的很好,你用什么sed版本? –
试试这个:
sed -i '/^\(}\)/ i new_function' file
他的工作是我在Debian。
是否有多个}?如果没有用$ Yourstuff}替换}像这样sed“s /}/$ yourstuff} /” –
@MikeWodarczyk,是的,会有更多的'}' – Kousha
有多个'}'没有前面的空白吗? – choroba