0

Let's say I have this data in a text file:

line1 
line2 
line3
line4
line5
...

I want to change this text file based on a pattern using line number e.g. line number mod 3,line contents:

1,line1
2,line2
3,line3
1,line4
2,line5
...

How can I achieve this (preferably using sed)?

1 Answer 1

1

This is hard to do in sed because it lacks arithmetic. However, there are a couple of ways you can do it with awk:

awk '{ printf "%d, %s\n", (linenum++ % 3) + 1, $0 }' lines.txt

or

awk '{ print (linenum++ % 3) + 1 ", " $0 }' lines.txt

In both cases, linenum is being used to count the lines, then the modulo operation is used to calculate the remainder of the line count divided by 3. The 1 is added to get the numbering scheme you requested.

printf provides a little "eye candy" to the program.

See man awk for details and other options.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .