替换整行,同时删除该特定行的换行符

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最好有)

Phi*_*pos 7

据我了解,您想将仅由单词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)


Sun*_*eep 5

我建议在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)


Tho*_*hor 5

使用 GNU sed,您可以将所有行读入内存-z并从那里进行匹配,例如:

sed -z 's/this\n/test/'
Run Code Online (Sandbox Code Playgroud)