Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 4 down vote accepted

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.

share|improve this answer

In sed, you can match the last line with $, and there is a command d which deletes the current line:

sed -i '$d' file.txt
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.