pbojinov
pbojinov

Reputation: 927

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

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,
        Address
        Zip Code
        County

Much Appreciated.

Upvotes: 3

Views: 1919

Answers (2)

potong
potong

Reputation: 58420

This might work for you (GNU sed):

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

Upvotes: 2

tripleee
tripleee

Reputation: 189397

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

Upvotes: 2

Related Questions