2/7/2019 - 1:10 PM

Modify files in place

We have two options here:

  • sed is a powerful stream editor although it also features a handy in-place/-i flag that may modify the source file. Unfortunately this is a non-standard FreeBSD extension and therefore results in unportable code. Simply put, some systems may have it, some others may not.
  • ex on the other hand is a standard Unix command-based editor that is a better fit for these kind of tasks.

Additionally sed is also capable of creating a backup file prior to modifying the original source file.


# Replace the shell executing the script
$ sed -i -e 's,bash,zsh,'

# sed can also create a backup file if an extension is provided to the -i flag
$ sed -i.bak -e 's/private/public/'
$ ls MyClass.*
# Replace the shell executing the script
$ ex - '+g/^#!/s,bash,zsh,' -cwq

# Comment all non-commentary lines
$ ex - '+g/^[[:space:]]*[^#]/s/^/#/' -cwq