Append text to the last line of a file in unix

2019-07-19 12:55发布

问题:

I want to append a colon character (:) at the end of the last line of a text file (not in a new line).

  • My file already has a \n character at the end so printf ":" >> file puts the colon in a new line.
  • Using sed '$s/$/:/' file > newfile works, but my file is ~100 MB so piping the whole thing just to add a single character seems unattractive.

Is there a better solution?

回答1:

You could go with dd and notrunc (tested on Linux 4.12):

printf ":" | dd of=file conv=notrunc bs=1 seek=$(( $(stat -c "%s" file) - 1))


标签: unix sed append