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

问题描述

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

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

(地址中的$指的是最后,而替换中正则表达式中的$指的是最后em>字符位置在每一行.它们是不相关的,但在某种意义上是相似的.)

(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.

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

08-12 11:59