5

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.

Questioner
  • 1,150
  • 5
  • 21
  • 35

2 Answers2

6

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.

Ulrich Dangel
  • 25,369
1

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
janos
  • 11,341