Command line scripting with ed

I just learned a little editing trick with ed and wanted to write some quick notes here.

Start with two files that are slightly different:

  1. $ cat file1
  2. the man o muse inform that many a way
  3. wound with his wisdom to his wished stay
  4. who wandered wonderous far when he the town
  5. of sacred troy had sacked and shivered down
  1. $ cat file2
  2. The man, o muse inform, that many a way
  3. wound with his wisdom to his wished stay
  4. who wandered wonderous far when he the town
  5. of sacred troy had sacked and shivered down

Diff them as an ed script by using the -e flag:

  1. $ diff -e file1 file2 > ed_script.diff

Check the ed script to see what it does (changes line 1 to the given line and finishes).

  1. $ cat ed_script.diff
  2. 1c
  3. The man, o muse inform, that many a way
  4. .

The ed script will need to write back to the file, so add a "w" to the end of the ed script.

  1. $ echo 'w' >> ed_script.diff

Now it looks like this:

  1. $ cat ed_script.diff
  2. 1c
  3. The man, o muse inform, that many a way
  4. .
  5. w

Process the file with ed, using the saved script:

  1. $ ed - file1 < script.diff

Now file1 has been updated to match file2:

  1. $ cat file1
  2. The man, o muse inform, that many a way
  3. wound with his wisdom to his wished stay
  4. who wandered wonderous far when he the town
  5. of sacred troy had sacked and shivered down

I thought it was interesting, because it might be useful in other scripts.