Command line scripting with ed and ex

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 (or ex) script by using the -e flag:

  1. $ diff -e file1 file2 > script1

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

  1. $ cat script1
  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: $ echo 'w' >> ed_script.diff

EDIT: there is a better way using %p -- for example:

  1. cat script1; echo '%p' | ex - oldfile

Or even using multiple scripts:

  1. cat script1 script2 script3; echo '%p' | ex - oldfile

Process the file with ed (or ex), 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.

Update: I found a use for it: Using ex to bulk-edit files