ed command: Delete from line 1 until the first blank line

1,/.../ means the range from the 1st line to a line matching the pattern between the /.

/^[ ]*$/ matches a line that contains 0 or any number of spaces [ ]* from the beginning ^ to the end $ of the line.
It is unclear if the code in the question is intentional and if it is an exact copy from the book. Brackets around a single space are not necessary. Maybe the original author wanted to have a space and a tab character between the brackets, which could be replaced with the character class [[:blank:]].

d is the command to delete the line

w write the file

q quit the editor

Those commands are sent to ed via a here document, indicated by the << EOF. The EOF string is a semi-arbitrary name that is paired to the other EOF four lines down. Leaving the EOF unquoted means that any variables in the intervening lines will be expanded.

The other thing to note here is the example's unquoted $1. The ed command/script will execute against the first positional parameter (argument to the script or function) subject to further whitespace splitting and filename generation. The argument really should be quoted. For further reading, see Why does my shell script choke on whitespace or other special characters? and Security implications of forgetting to quote a variable in bash/POSIX shells.


Command and input

The $1 is the file name to be edited and everything between the EOFs are commands to ed.

Blow by blow description of 1,/^[ ]*$/d

  • 1, start from line 1 and in this case continue until first occurrence of search string
  • / indicates we are about to search for a string
  • ^ indicates we want to match the start of the line in the file
  • [ indicates we are about to specify many characters
  • '' we want to match a space - normally there would be more characters here
  • ] finished specifying characters
  • * we want to match 0 or more spaces (or whatever characters between [])
  • $ until the end of the line in the file
  • / closing the search
  • d delete the line

Then the next line w writes the changes, and q quits ed.

Effect

If the file's ($1) line one is empty or has only spaces (no tabs) then it will be removed.

Tags:

Ed