简体   繁体   English

你如何用sed替换匹配的第一行?

[英]How do you replace the first line that of a match with sed?

I am currently trying to replace lines in the following file: 我目前正在尝试替换以下文件中的行:

Music_location = /home/music
Music_location = /home/music
Pictures = /home/pictures

How do I only replace the first "/home/music" without saying what line it is on? 我怎么只更换第一个“/ home / music”而不说它是什么线? Thanks! 谢谢!

Using awk you can do this: 使用awk你可以这样做:

awk '!p{sub(/\/home\/music/, "/foo/bar"); p=1} 1' file
Music_location = /foo/bar
Music_location = /home/music
Pictures = /home/pictures

In sed: 在sed中:

sed '0,/home\/music/s_/home/music_/foo/bar_' foo.txt

This starts at line 0, stops when it finds /home/music, and then replaces the /home/music with /foo/bar. 这从第0行开始,在找到/ home / music时停止,然后用/ foo / bar替换/ home / music。 In the "s_/home/music_/foo/bar_" part, I have changed the normal delimiter, a slash, to an underscore, so that I may use slashes in my regular expression. 在“s_ / home / music_ / foo / bar_”部分中,我将正常分隔符(斜杠)更改为下划线,以便我可以在正则表达式中使用斜杠。

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

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