1

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? Thanks!

NSPredator
  • 434
  • 4
  • 10
  • possible duplicate of [How to use sed to replace only the first occurrence in a file?](http://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file) – rahul May 21 '15 at 18:07
  • This question has already been asked and answered here - https://stackoverflow.com/questions/148451/how-to-use-sed-to-replace-only-the-first-occurrence-in-a-file – rahul May 21 '15 at 18:14

2 Answers2

2

Using awk you can do this:

awk '!p{sub(/\/home\/music/, "/foo/bar"); p=1} 1' file
Music_location = /foo/bar
Music_location = /home/music
Pictures = /home/pictures
anubhava
  • 713,503
  • 59
  • 514
  • 593
1

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

bkmoney
  • 1,226
  • 1
  • 9
  • 19