我有这样的文件:
class SomeClass
extends anotherClass
with moreClassA
with moreClassB {
//do some crazy stuff
}
我想再添加一个类,如下所示:
class SomeClass
extends anotherClass
with moreClassA
with moreClassB
with oneMoreClassIwant {
//do some crazy stuff
}
我尝试使用 sed 进行替换,如下所示:
sed -E "s/(Class SomeClass[A-Za-z \n]+)\\{/\1with OneMoreClassIWant/" tmp.scala
但它不适用于多行匹配。
我还注意到一个例子这个帖子但未能使其适应我的情况。
答案1
使用任何 awk:
$ cat tst.awk
{ rec = rec $0 RS }
END {
old = \
"class SomeClass" RS\
" extends anotherClass" RS\
" with moreClassA" RS\
" with moreClassB {" RS\
" //do some crazy stuff" RS\
"}"
new = \
"class SomeClass" RS\
" extends anotherClass" RS\
" with moreClassA" RS\
" with moreClassB" RS\
" with oneMoreClassIwant {" RS\
" //do some crazy stuff" RS\
"}"
if ( s = index(rec,old) ) {
rec = substr(rec,1,s-1) new substr(rec,s+length(old))
}
printf "%s", rec
}
$ awk -f tst.awk file
class SomeClass
extends anotherClass
with moreClassA
with moreClassB
with oneMoreClassIwant {
//do some crazy stuff
}
答案2
这似乎有效:
xargs -0 < data | sed -z 's/\(class.*\){/\1\n with anotherMoreClass {/'
或者
tr '\n' '\0' < data | sed 's/\(class.*\){/\1\n with anotherMoreClass {/' | tr '\0' '\n'
您可以在此部分中指定类名称(SomeClass
在您的情况下):\(class.*\)
如下所示:
xargs -0 < data |\
sed -z 's/\(class[[:blank:]]\{1,\}SomeClass.*\){/\1\n with anotherMoreClass {/'
或者
tr '\n' '\0' < data |\
sed 's/\(class[[:blank:]]\{1,\}SomeClass.*\){/\1\n with anotherMoreClass {/' |\
tr '\0' '\n'