0

The original file would be:

line 1
line 2
line 3
line 4
line 5
.
.
.
line N

and I want to append some text (e.g."word") every X lines until the end of the file is reached, like this: (X=2 in example)

line 1 word
line 2
line 3 word
line 4
line 5 word
line 6
line 7 word
.
.
.
line N

N is of the order of 100000. With the program I made (using sed) I had to wait for about 15 minutes to finish. I'm sure there is a much quicker way to do it.

Cyrus
  • 69,405
  • 13
  • 65
  • 117
Ivan
  • 5
  • 3

3 Answers3

0

With GNU sed:

sed '1~2s/.*/& word/' file
Cyrus
  • 69,405
  • 13
  • 65
  • 117
  • I'm surprised with the simplicity of the answer. Would you recommend me a good book for learning bash and GNU sed? Thanks – Ivan Nov 11 '16 at 20:58
  • @Ivan: I agree with [janos' suggestion](http://stackoverflow.com/questions/40555777/how-do-i-quickly-append-using-sed-the-same-word-to-the-end-of-many-different-lin/40555858#comment68350513_40555869), take a look at the [sed tag wiki](http://stackoverflow.com/tags/sed/info) and see [The Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/3776858), too. – Cyrus Nov 14 '16 at 23:02
0

You forgot to mention what sed command you used. This method (GNU sed) to append "word" at the end of every 2nd line is simple and should be very fast:

sed -e '1~2s/$/ word/' file

If you want to overwrite the file in-place, add the -i flag:

sed -ie '1~2s/$/ word/' file
janos
  • 109,862
  • 22
  • 193
  • 214
  • That was a pretty fast answer. I will ask the same as I ask to Cyrus. Would you recommend me a good book for learning bash and GNU sed? Thanks in advanced – Ivan Nov 11 '16 at 21:01
  • Absolutely, look at the bottom of the [Bash tag wiki](http://stackoverflow.com/tags/bash/info). This is my top recommendation for all Bash learners. – janos Nov 11 '16 at 21:05
0

sed is for simple subsitutions on individual lines that is all. For any other task you should use awk for simplicity, clarity, portability, maintainability, efficiency, and most other desirable attributes of software:

$ seq 10 | awk -v n=2 '{print $0 (NR%n == 1 ? " word" : "")}'
1 word
2
3 word
4
5 word
6
7 word
8
9 word
10

$ seq 10 | awk -v n=3 '{print $0 (NR%n == 1 ? " word" : "")}'
1 word
2
3
4 word
5
6
7 word
8
9
10 word

The above will work in any awk on any UNIX box and can be easily tweaked to do anything else you want to do additionally or differently in future.

Don't waste your time learning arcane sed constructs to do anything other than s/old/new/ - learn how to do whatever it is you want to do the right way by reading Effective Awk Programming, 4th Edition, by Arnold Robbins.

Ed Morton
  • 157,421
  • 15
  • 62
  • 152