2

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.

Kyounge1
  • 23
  • 3

1 Answers1

2

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • This works, thank you so much! I'm still confused though, is $(command) specific to ed? in the info page it says this: " We can run Unix shell ('sh') commands from inside 'ed' by prefixing them with <!> (exclamation mark, aka "bang"). For example: *!date" I am confused as to why that syntax wouldn't work. – Kyounge1 Feb 08 '20 at 01:39
  • No, that's a standard shell command substitution; the here document is treated like a double-quoted string if you don't escape any part of the delimiter. That's how your `w` command writes to the current name; `ed` doesn't see `$arg`, but rather the value of the parameter as expanded by the shell. (By the way, `w` alone is sufficient; without a file name, `w` writes to the current file name, which is initialized to the argument to `ed`.) – chepner Feb 08 '20 at 01:41
  • `!` is a command itself, like `a`, or part of the syntax of the `r` command. It's not an arbitrary command substitution operator. – chepner Feb 08 '20 at 01:42
  • Oh, that makes sense! Thank you for your help! – Kyounge1 Feb 08 '20 at 01:43
  • Actually, given that the default output of `date` is reproduced with `%a %b %e %H:%M:%S %Z %Y`, don't worry about the second version at all :) – chepner Feb 08 '20 at 01:43