How can I remove the last comma separator from the end of a file?
sed -i '$s/,$//' file
That is, on the last line (
$) substitute (
s) the comma at the end of the line (
,$) by nothing.
The change will be done in-place due to the
sed '$s/,$//' <file >file.new && mv file.new file
Note: Someone suggested an edit to change "on the last line" to "last on the line" (or something similar). This is wrong. When
$ is used to specify an address (a line where to apply an editing command), then it refers to the last line of the stream or file. This is different from using
$ in a regular expression.
For in-place editing you could use
ed - conveniently, it sets the position to the last line by default on opening so you don't need to address the last line explicitly:
ed file s/,$// wq
Or, as a one-liner
printf 's/,$//\nwq\n' | ed -s file
In general, I'd probably go with the straightforward
sed solution. However, if your input files are huge, you might want a solution that doesn't take the time to read through the whole file just to edit the last couple of bytes.
If you are 100% sure your input file ends with a comma followed by a newline, you can use
truncate to lop off these last two characters, and then re-append a final newline:
filesize=$(stat -L --format "%s" lastcomma.txt) truncate --size $((filesize - 2)) lastcomma.txt echo >> lastcomma.txt
This assumes a distro that includes GNU truncate or equivalent.
@StéphaneChazelas points out that GNU
truncate now supports
truncate -s -2 file to shorten the file by two bytes; if you have this version, the above simplifies to:
truncate --size -2 lastcomma.txt echo >> lastcomma.txt