简体   繁体   English

如何使用 SED 命令在模式匹配前插入一行

[英]How To Use SED Command To Insert A Line Before A Pattern Match

After running command sed -i "/class MySQLPagedResultsajax/i Thing I Wish To Add;" /File/Location/运行命令后sed -i "/class MySQLPagedResultsajax/i Thing I Wish To Add;" /File/Location/ sed -i "/class MySQLPagedResultsajax/i Thing I Wish To Add;" /File/Location/

The result I get are as follows:我得到的结果如下:

Thing I Wish To Add;class MySQLPagedResultsajax 

Whereas I want to achieve this:而我想实现这一目标:

Thing I Wish To Add;
class MySQLPagedResultsajax 

Please Help As I Want A Single Line Command Solution As This Needs To Be Done On Multiple Files And I Will Be Using Excel To Create Separate Commands For Each File.请帮助,因为我想要一个单行命令解决方案,因为这需要在多个文件上完成,我将使用 Excel 为每个文件创建单独的命令。

Try this:尝试这个:

sed -i '/class MySQLPagedResultsajax/s/^/Thing I Wish To Add;\n/'

Or before you are sure, try this first and check the output on console:或者在你确定之前,先试试这个并检查控制台上的输出:

sed -e '/class MySQLPagedResultsajax/s/^/Thing I Wish To Add;\n/'

s is the s ubstitute command. s4的ubstitute命令。
^ means the beginning of the line. ^表示行的开头。
\\n a newline. \\n换行。

Just use awk for anything other than a simple s/old/new:只需将 awk 用于简单的 s/old/new 以外的任何内容:

awk '/class MySQLPagedResultsajax/{print "Thing I Wish To Add;"} 1' file

add -i inplace to do pseudo-inplace editing with GNU awk like you can do pseudo-inplace editing with GNU sed by adding - i.添加-i inplace以使用 GNU awk 进行伪就地编辑,就像您可以通过添加- i 使用 GNU sed 进行伪就地编辑一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM