Bash – How to Remove Text on the Last Line of a File

bash

I am using a Bash shell script to construct a text file that contains a Javascript array. As far as I understand with Javascript, the last item in an array can't have a comma. In my Javascripts, that gives me errors.

I have a list of items that is generated with other code, and the result looks something like this:

text0161: "blah",
text0162: "blah blah",
text0163: "blah blah blah",

I need to take the very last line, text0163: "blah blah blah", and remove the trailing comma, so it becomes text0163: "blah blah blah".

At this point in my processing, there is nothing after text0163: "blah blah blah", so I can just look for the very last line in the file and remove the comma. However, the contents of the line might change, so it won't always be exactly text0163: "blah blah blah",. It might become just about anything else, like text2020: "doobie doobie doo",.

I know I can use sed to delete the comma, like this:

sed -i 's@,@@g' file.txt

But I don't know how to only do that on the last line.

Best Answer

You can specify the address of your specific command/regular expression. The last line is represented by $, so in your case it would be:

sed -i '$ s/,$//' file.txt

Please note that i replaces your @ with / as they are more commonly used in regular expressions.

This regular expression also removes only the comma at the end of the line, e.g. if there is a space after the comma or the comma is in the quoted text it will not be removed.

Related Question