Nor*_*tfi 4 sed regular-expression
我正在尝试替换(用sed
)包含特定单词的整行和末尾的换行符。这里的测试文件:
this # target for substitution
this is a test
another test?
Run Code Online (Sandbox Code Playgroud)
现在,我已经在这里发布了,并且从链接的帖子中,我了解了如何以某种方式执行此操作:
sed 's/^this$/test/g' testfile
Run Code Online (Sandbox Code Playgroud)
这是有效的,或者至少看起来如此,因为单词末尾的换行符this
仍然存在:
test # target for substitution but newline is still there
this is a test
another test?
Run Code Online (Sandbox Code Playgroud)
鉴于上述情况,我也完全意识到 sed
不能直接匹配换行符(尽管我记得我可以在某些版本的 中使用 '\n' sed
,但这无关紧要)。
我知道如何至少删除整个单词/行和换行符:
this # target for substitution
this is a test
another test?
Run Code Online (Sandbox Code Playgroud)
除了我需要替换它。
我怎样才能做到这一点?(sed
最好有)
据我了解,您想将仅由单词this
和以下换行符组成的行替换为test
,因此
foo
this
this is a test
Run Code Online (Sandbox Code Playgroud)
应该成为
foo
testthis is a test
Run Code Online (Sandbox Code Playgroud)
在sed
你可以简单地加入下一行与N
和取代一切到新行:
sed '/^this$/{N;s/.*\n/test/;}'
Run Code Online (Sandbox Code Playgroud)
我建议在perl
这里使用,语法与sed
这种情况没有什么不同:
$ cat ip.txt
this
this is a test
another test?
$ perl -pe 's/^this\n/XYZ/' ip.txt
XYZthis is a test
another test?
Run Code Online (Sandbox Code Playgroud)
使用 GNU sed,您可以将所有行读入内存-z
并从那里进行匹配,例如:
sed -z 's/this\n/test/'
Run Code Online (Sandbox Code Playgroud)