Remove comma from last line

How to remove a comma from the last line of a file? Here is the file:

# cat ox_data_archive_r_20120727.json {"name": "secondary_ua","type":"STRING"}, {"name": "request_ip","type":"STRING"}, {"name": "cb","type":"STRING"}, 

The following will remove the comma from all three lines.

 # sed 's/,$/\ /' ox_data_archive_r_20120727.json {"name": "secondary_ua","type":"STRING"} {"name": "request_ip","type":"STRING"} {"name": "cb","type":"STRING"} 

I need to remove only the last comma. Thus, the result should look something like this:

 # cat newfile.json {"name": "secondary_ua","type":"STRING"}, {"name": "request_ip","type":"STRING"}, {"name": "cb","type":"STRING"} 
+4
source share
3 answers
 $ cat input.txt {"name": "secondary_ua","type":"STRING"}, {"name": "request_ip","type":"STRING"}, {"name": "cb","type":"STRING"}, $ sed '$s/,$//' < input.txt {"name": "secondary_ua","type":"STRING"}, {"name": "request_ip","type":"STRING"}, {"name": "cb","type":"STRING"} 

From the GNU sed documentation:

$ : this address corresponds to the last line of the last input file or the last line of each file if the -i or -s options are specified.

+16
source

This should work:

 sed '$ s/,$//g' input_file 
  • The first $ selects the last line.

You can add -i and sed apply changes to input_file .

+4
source

Awk's answer is certainly more verbose than sed:

 awk 'NR>1 {print prev} {prev=$0} END {sub(/,$/,"", prev); print prev}' file 
0
source

Source: https://habr.com/ru/post/1433819/


All Articles