How can I add a comma at the end of every line except the last line?

前端 未结 4 1735
星月不相逢
星月不相逢 2020-12-07 22:36

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

I have this now:

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

I w

相关标签:
4条回答
  • 2020-12-07 23:17

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

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

    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.

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

    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.

    0 讨论(0)
  • 2020-12-07 23:29
    vim <file-name>
    
    :%s/$/,/g
    

    To remove

    :%s/,//g
    
    0 讨论(0)
  • 2020-12-07 23:39

    You can use something like this:

     sed 's/$/,/' file.txt > file_with_added_commas.txt
    

    This will substitute the end of the line with a ',' and write it to file_with_added_commas.txt

    For more information refer to: add text at the end of each line

    0 讨论(0)
  • 2020-12-07 23:40

    Keep it simple, just use awk:

    $ awk '{printf "%s%s",sep,$0; sep=",\n"} END{print ""}' file
    {...},
    {...},
    {...},
    {...}
    
    0 讨论(0)
提交回复
热议问题