Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izimbra/7168469 to your computer and use it in GitHub Desktop.
Save izimbra/7168469 to your computer and use it in GitHub Desktop.
Replaces first occurrence of a string in a file using sed. This was tried and worked in OS X 10.9. #osx #shell #sed
sed '1,/string/ s/string/replacement/' file
@izimbra
Copy link
Author

izimbra commented Oct 26, 2013

This comes from StackOverflow. Some people there suggested using sed '0,/string/ s/string/replacement' but this didn't work for me on OS X 10.9.

Solution sed 's/string/replacement/1' works as well, in case of one occurrence of the string per line. Otherwise, sed will replace all occurrences of the string within the first line where it's found.

@Ojasv-Singh-Zeotap
Copy link

to change in a text file (inplace), sed -i '.txt' '1,/string/ s/string/replacement/g' ~/.zshrc works fine for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment