shantanuo
shantanuo

Reputation: 32316

remove comma from last line

How do I remove the comma from the last line of the 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 3 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 the last comma only. So the output should look something like this...

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

Upvotes: 10

Views: 20858

Answers (3)

user647772
user647772

Reputation:

$ 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 documentation of GNU sed:

$: This address matches the last line of the last file of input, or the last line of each file when the -i or -s options are specified.

Upvotes: 33

glenn jackman
glenn jackman

Reputation: 246807

The awk answer is certainly more verbose than the sed:

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

Upvotes: 0

Sicco
Sicco

Reputation: 6271

This should work:

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

You could add -i and sed will apply the changes to your input_file.

Upvotes: 7

Related Questions