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
  • 464
  • 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
  • 761,203
  • 64
  • 569
  • 643
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,256
  • 1
  • 11
  • 19
  • Make sure you drop a note about your use of `_` as alternate delimiters. Most will know, but the person you are helping might be left scratching his head. – David C. Rankin May 22 '15 at 04:34