匹配模式时如何在行尾添加文本?


8

输入:

line1 with the PATTERN that contains ( ) 
line2 with the PATTERN that contains ( ) 
lineN with the PATTERN that contains ( ) 

输出:

line1 with the PATTERN that contains ( ) ;
line2 with the PATTERN that contains ( ) ;
...
lineN with the PATTERN that contains ( ) ;

我尝试了这个:

find . -name "test.txt" -print | xargs sed -i "/PATTERN/ s/$)/); /g"

但这没用。

Answers:


3
perl -ipe 's/$/;/ if /PATTERN/'

;如果该行包含,则会在末尾添加PATTERN


3

$行的末尾匹配,所以你的模式应该是)$,而不是$)像在您的示例。

另外,您xargs在这里不需要,使用以下-exec标记更安全fine

find . -name test.txt -exec sed -i '/PATTERN/ s/)$/); /' '{}' +

如果您的find版本+最后无法使用,请\;改用(谢谢@ glenn-jackman):

find . -name test.txt -exec sed -i '/PATTERN/ s/)$/); /' '{}' \;

最后,不需要gs/something$//习惯用法中使用标志,因为$每行仅出现一次。


1
如果发现允许,您可以使用-exec ... +代替来获得一些效率-exec ... \;
glenn jackman 2014年

2

假设这PATTERN是实际的( ),并且可能在之间插入某些东西,( )并且它们不一定位于行尾:

sed -i '/(.*)/ s/$/ ;/' test.txt


0

尝试:

sed --in-place '/PATTERN/s/.*/&;/' /path/to/file.txt
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.