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

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

问题描述

我想在任何现有 #includes 之前使用额外的 include 指令更新大量 C++ 源文件.对于此类任务,我通常使用带有 sed 的小型 bash 脚本来重写文件.

I would like 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.

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

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

如果我使用

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

它替换所有#includes.

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---

或者,如果您愿意:编者注:仅适用于 GNU sed.

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

sed '0,/foo/s//bar/' file 

来源

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

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