开发者

sed - inserting a comma after every 4th line in plain text file

开发者 https://www.devze.com 2023-03-30 05:08 出处:网络
I am trying to insert a comma after the values on line 1, 4, 8, etc using sed, sed \'0-4 s/$/,/\' in.txt > in2.txt

I am trying to insert a comma after the values on line 1, 4, 8, etc using sed,

sed '0-4 s/$/,/' in.txt > in2.txt

For some reason this isn't working so I was wondering if anyone has any solutions doing this using awk, sed, or any other methods.

The error I am getting is

sed: 1: "0-4 s/$/,/": invalid command code -

Currently my data looks like this:

        City
        Address
        Zip Code
        County

and I was trying to format it like this

        City,
        Addre开发者_如何转开发ss
        Zip Code
        County

Much Appreciated.


0-4 indeed is not well-formed sed syntax. I would use awk for this, but it is easy to do it with either.

sed 's/$/,/;n;n;n' file

which substitutes one line and prints it, then prints the next three lines without substitution, then starts over from the beginning of the script; or

awk 'NR % 4 == 1 {sub(/$/,",")} {print}'

which does the substitution if the line number modulo 4 is 1, then prints unconditionally.

Sed's addressing modes are sometimes a tad disappointing; there is no standard way to calculate line offsets, relative or in reference to e.g. the end of the file. Of course, awk is more complex, but if you can only learn one or the other, definitely go for awk. (Or in this day and age, Python or Perl -- a much better investment.)


This might work for you (GNU sed):

sed '1~4s/$/,/' file
0

精彩评论

暂无评论...
验证码 换一张
取 消