linuxscriptingshed

How to append a line with the output of a command using ed


I am writing a bourne shell script in Linux, and I am using ed to append text to the end of the file. I MUST use ed to do this task.

What I need the appended text to look like is this

Modified on: current_date

Where current_date is the output of the date command

The code I am using is this:

ed -s $arg << END
a
Modified on: !date
.
w $arg
q
END

Clearly though, this would just put the string "!date" instead of the output of the date command.

What is the best way to accomplish this goal?

So far, I have tried to use the commands '(.,.)s /RE/REPLACEMENT/', x, and j to no avail, and I'm not seeing a command that would be able to do this in the info page for ed.


Solution

  • Just like you are expanding $arg in the script, so you can expand a command substitution that runs date.

    ed -s $arg <<END
    a
    Modified on: $(date)
    .
    w $arg
    q
    END
    

    I'd like to suggest something like

    ed -s $arg <<END
    r !date +'Modified on \%F'
    w $arg
    q
    END
    

    as well (replace %F with whatever format string duplicates the default output format), but I can't seem to get it quite right. The backslash prevents ed from replacing the % with the current file name, but the backslash remains in the output as well. I'm not sure how to overcome that.