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

Source: https://stackoverflow.com/a/33186317

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

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

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