0

I see

<command> >> <filepath> appends the command line to the file

and

<command> > <filepath> replaces the entire contents of the file with the command given passed.

How to pass the command to the file so that only the last line of the file is overwritten?

1 Answer 1

1

That's not built in to the shell in the same way simple overwrite and append are. You have to do it in two steps, first remove the last line, then append:

X=$(head -n -1 filepath)
echo "$X" > filepath
command >> filepath

Or you can overwrite with the new contents all at once:

X=$(head -n -1 test)
(echo "$X"; command) > test

Note that in both cases, we capture the old lines that we want to keep in a variable first as a separate command. This is because as soon as a command with a ">" directive begins executing, the shell will clear the file, and any attempt to read those lines will be too late.

1
  • Oh ok! Didn't know about capturing part of the string :-) The net result is just what I wanted. Thanks!
    – Karthik C
    Jun 2, 2013 at 17:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .