如何从文件的最后一行删除逗号? 这是文件:
# cat ox_data_archive_r_20120727.json
{"name": "secondary_ua","type":"STRING"},
{"name": "request_ip","type":"STRING"},
{"name": "cb","type":"STRING"},
以下内容将删除所有3行中的逗号。
# sed 's/,$/\ /' ox_data_archive_r_20120727.json
{"name": "secondary_ua","type":"STRING"}
{"name": "request_ip","type":"STRING"}
{"name": "cb","type":"STRING"}
我只需删除最后一个逗号。所以输出看起来应该是这样......
# cat newfile.json
{"name": "secondary_ua","type":"STRING"},
{"name": "request_ip","type":"STRING"},
{"name": "cb","type":"STRING"}
答案 0 :(得分:22)
$ 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"}
来自GNU sed的文档:
$
:此地址与最后一个输入文件的最后一行匹配,或者在指定-i
或-s
选项时匹配每个文件的最后一行。
答案 1 :(得分:4)
这应该有效:
sed '$ s/,$//g' input_file
$
选择最后一行。您可以添加-i
,sed
会将更改应用到input_file
。
答案 2 :(得分:0)
awk答案肯定比sed更加冗长:
awk 'NR>1 {print prev} {prev=$0} END {sub(/,$/,"", prev); print prev}' file