如何使用sed来只替换文件中的第一次出现? [英] How to use sed to replace only the first occurrence in a file?

查看:1684
本文介绍了如何使用sed来只替换文件中的第一次出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在任何现有的#includes之前使用额外的include指令更新大量的C ++源文件。对于这种任务,我通常使用一个小的bash脚本与sed重写文件。



如何让sed只替换文件中第一次出现的字符串,而不是替换每一个字符?



如果我使用

  sed s / #include / #includenewfile.h 

它会替换所有的#includes。



也欢迎提供替代建议以实现相同的目的。

解决方案

 #sed脚本只在第一次出现时将foo更改为bar
1 {x; s / ^ / first /; x;}
1 ,/ foo / {x; / first / s ///; x; s / foo / bar /;}
#---脚本结束---



或,如果您愿意:编辑笔记:使用 GNU sed c>

  sed'0,/ RE / s / / to_that /'file 

来源


I want to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task I normally use a small bash script with sed to re-write the file.

How do I get sed to replace just the first occurrence of a string in a file rather than replacing the every occurrence?

If I use

sed s/#include/#include "newfile.h"\n#include/

it replaces all #includes.

Alternative suggestions to achieve the same thing are also welcome.

解决方案

 # sed script to change "foo" to "bar" only on the first occurrence
 1{x;s/^/first/;x;}
 1,/foo/{x;/first/s///;x;s/foo/bar/;}
 #---end of script---

or, if you prefer: Editor's note: works with GNU sed only.

sed '0,/RE/s//to_that/' file 

Source

这篇关于如何使用sed来只替换文件中的第一次出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆