Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
add comment

1 Answer 1

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
add comment

Your Answer

 
discard

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.