Script file edits with the "ed" editor
brian_s 270002K5X3 Visits (10819)
The "ed" editor has for the most part been forgotten as a piece of UNIX history. But it can still be very handy when scripting file edits, especially when the script must work across multiple UNIX variants.
ed is a "line editor". What this basically means is it is designed to work on a teletype (aka keyboard with a printer). This makes it challenging to use as an interactive editor, but it is perfect for scripting. ed is part of the Single UNIX Specification so it should exist on any system claiming to be UNIX, so it is a good utility to rely on in your scripts if they are cross platform.
Many systems such as Linux support the "sed" command with the "-i" flag that specifies the file should be edited in place. Unfortunately systems such as AIX don't support an inline edit mode with sed so you either have to create temporary files (ugly in my opinion) or use something different such as ed.
All ed commands specify a range of lines (or a "," for the entire file), and then a command. For example, within ed you can display lines 1 through 5 with the command "1,5l", or you can display the entire file with ",l".
Here are some example command lines to edit files that can be used from scripts.
First off, we will edit the "sshd_config" file and replace the line "#Port 22" with "Port 222". To do this we use printf to pipe the commands we want to run to ed. In between each ed command we put a "\n" to put a carriage return / new line.
$ cat sshd_config | grep "Port "
So in this example we are telling ed to first run ",s/^#Port 22$/Port222". The first comma means apply to all lines, the "s" means search, the "^#Port 22$" means to look for a line that begins (^) and ends ($) with "Port 22". The "/" means replace, and the "Port 222" is what we want it to be replaced with. The "w" means write the file. The "q" means quit.
Here is an example of adding a line to a file. For example, lets say we want to add the comment line "Updated port to 222 on 8/19/12" to the top of the sshd_config file:
The "1" means to go to line 1, the "i" means insert mode, the "#Updated port to 222 on 8/19/12" is the text we are adding, the "." on the line by itself means to go back to command mode, the "w" is write, and the "q" is quit.
You can also easily delete lines. Lets suppose for example we decide to delete the "Port 222" line from the file:
$ cat sshd_config | grep ^Port
As you can see ed is a powerful utility to edit files from scripts quickly and easily.