如何在除最后一行之外的每行末尾添加逗号? [英] How can I add a comma at the end of every line except the last line?

查看:78
本文介绍了如何在除最后一行之外的每行末尾添加逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在这种文件的每一行的末尾添加逗号,除了最后一行:

I want add a comma at the end of every line of this kind of file except the last line:

我现在有这个:

{...}
{...}
{...}
{...}

我想要这个:

{...},
{...},
{...},
{...}

如何在命令行中执行此操作? sed命令可以吗?

How can I do it with the command line? Is it possible with sed command?

推荐答案

以下sed脚本的地址表达式$!与不是最后一行的行相匹配,并且替换动作s/$/,/加上逗号在行尾旁边.

The following sed script has an address expression $! which matches lines which are not the last, and a substituton action s/$/,/ which adds a comma next to the end of line.

sed '$!s/$/,/' file

(地址中的$指代最后一个,而正则表达式中的$指代每个字符上的最后一个字符位置线.尽管在某种意义上相似,它们却无关紧要.)

(The $ in the address refers to the last line while the $ in the regular expression in the substitution refers to the last character position on every line. They are unrelated, though in some sense similar.)

这会将file的修改内容打印到标准输出;重定向到其他文件以将其保存到文件,或者如果sed支持,则使用sed -i. (某些变体要求-i选项的参数为空,特别是* BSD/OSX sed.)

This prints the modified contents of file to standard output; redirect to a different file to save them to a file, or use sed -i if your sed supports that. (Some variants require an empty argument to the -i option, notably *BSD / OSX sed.)

如果您的任务是从不合法的东西生成有效的JSON,则我对此方法表示怀疑.结构化格式应使用了解结构化格式的工具进行操作,而不是基本的面向行的工具;但是如果这可以帮助您将面向行的数据转换为正确的JSON,则可能是有效的用法.

If your task is to generate valid JSON from something which is not, I'm skeptical of this approach. Structured formats should be manipulated with tools which understand structured formats, not basic line-oriented tools; but if this helps you transform line-oriented data towards proper JSON, that's probably a valid use.

...作为事后的想法,也许您也想将输出包装在一组方括号中.然后,它实际上是技术上有效的JSON(假设每一行本身就是一个有效的JSON片段).

... As an afterthought, maybe you want to wrap the output in a set of square brackets, too. Then it's actually technically valid JSON (assuming each line is a valid JSON fragment on its own).

sed '1s/^/[/;$!s/$/,/;$s/$/]/' file

在第一行(地址表达式1)上,在行(s/^/[/)开头的方括号中替换.在不是最后一行的行上,添加一个逗号,如上所述.在最后一个 行(地址表达式$)上,在行(s/$/]/)的末尾添加一个方括号.如果您喜欢换行符而不是分号,那很好.许多sed方言还允许您将其拆分为多个-e自变量.

On the first line (address expression 1) substitute in an opening square bracket at beginning of line (s/^/[/). On lines which are not the last, add a trailing comma, as above. On the line which is the last (address expression $) add a closing square bracket at the end of line (s/$/]/). If you prefer newlines to semicolons, that's fine; many sed dialects also allow you to split this into multiple -e arguments.

这篇关于如何在除最后一行之外的每行末尾添加逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆