将文本替换为前置字符串和后置字符串
我有一个文件,其中有一些具有公共字符串的行:
_report_file <<
所以上面的文本可以是任何东西,但它以分号(;)结尾 例如,请参见下面的行:
CACUP_updater::_report_file << "The job has terminated." << endl;
该行的另一个示例可以是:
_report_file << "The job is reading." << endl;
我需要将 abc;
作为前置字符串附加,将 xyz;
作为后置字符串附加到该行,以便该行看起来
abc;CACUP_updater::_report_file << "The job has terminated." << endl;xyz;
基本上我想搜索 "_report_file <<"
,选择完整的行并在前后添加一些文本。 我怎样才能在 sed 或 perl 或 awk 中做到这一点。
I have file in which there are certian lines which have common string:
_report_file <<
SO the text around this above can be any thingbut it ends with semiclon(;)
for eg see the line below:
CACUP_updater::_report_file << "The job has terminated." << endl;
another example of the line can be:
_report_file << "The job is reading." << endl;
i need to append abc;
as pre string and xyz;
as post string to that line so that the line looks like
abc;CACUP_updater::_report_file << "The job has terminated." << endl;xyz;
basically i want to search for "_report_file <<"
,select the complete line and pre and post append some text.
how can i do this in sed or perl or awk.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Perl 方式:
或
A perl way:
or
这也会为您提供该文件的备份副本。
That'll give you a backup copy of the file too.
编辑以回复您更新的问题。我认为你做错了:)
我建议你这样做:
这样,你可以在 C++ 中定义一个像
But Why? 这样的
您可以在其他地方阅读有关安全宏的所有内容1。
您将获得更大的灵活性。您稍后可以一次性更改所有实例。
您可以委托给一个函数
您可以声明一个临时
stringstream
并将结果文本写入整个其他介质(网络?fwrite?内存缓冲区?两个流?)。您可以根据全局 falg 进行有条件的日志记录,而不必通过代码重复对其进行检查。
好吧,你明白了:它几乎是DRY原理。
示例输入:
示例输出:
例如
perl -i.bck test.cpp
的结果是 2:宏实现的一些想法:
这展示了如何
abc;
或xyz;
您的想法:)。
文件的输出为:
stderr 的输出取决于
verbose
标志1 想象一下如果
if (b) _report_file << 会发生什么“好的!” << std::endl;
?2 请注意,创建了一个备份文件:
test.cpp.bck
Edit in response to your updated question. I think you're doing it wrong :)
I suggest you do it this way instead:
That way, you can, in C++, define a macro like
But Why?
You can read all about safe macros elsewhere 1.
You get way more flexibility. You can later change all instances at one point.
You can delegate to a a function
You could declare a temporary
stringstream
and write the resulting text to a whole other medium (network? fwrite? memory buffer? two streams?).You could make the logging conditional depending on a global falg without having to duplicate the check for it throughour your code.
Well you get it: it pretty much the DRY principle.
Sample input:
Sample output:
The result of, e.g.
perl -i.bck test.cpp
is 2:Some ideas for implementations of the macro:
This shows how you can
abc;
orxyz;
you had in mind :).
The output to the file is:
The output to the stderr depends on the
verbose
flag1 just imagine what would happen if
if (b) _report_file << "ok!" << std::endl;
?2 note that a backup file is created:
test.cpp.bck