LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   insert line in file every 1000th line via sed or in vi (https://www.linuxquestions.org/questions/programming-9/insert-line-in-file-every-1000th-line-via-sed-or-in-vi-4175621330/)

tiny.deluxe 01-10-2018 03:24 AM

insert line in file every 1000th line via sed or in vi
 
Hi all,
you helped me out once and I hope you can do it once again.;)
My problem:
I have a more or less big file with many update statements (about 590000)for execution in an Oracle database. Now I need to insert a "commit" line after every 1000th line.
Do you have any idea to do this with 'sed' or directly in 'vi'?

Thanks in advance for your help.

Best regards
Elke

Turbocapitalist 01-10-2018 04:50 AM

Some versions of sed can do it.

Code:

sed -e '0~5 s/$/\nfoo/'
sed -e '0~5 afoo'

Check your manual page to see if the 'step' option is there:
first~step

Match every step'th line starting with line first. For example,
``sed -n 1~2p'' will print all the odd-numbered lines in the
input stream, and the address 2~5 will match every fifth line,
starting with the second. first can be zero; in this case, sed
operates as if it were equal to step. (This is an extension.)
Otherwise, if you need something portable, you could try awk

Code:

awk '{print;} !(++a%5) {print "foo";}'
Edit: the 'a' command is shorter than the 's' command

tiny.deluxe 01-10-2018 05:39 AM

@Turbocapitalist:
thanks a lot. The second advice (awk) did it. sed replaced each fifth line with "commit" instead of inserted it.

Best Regards
Elke

Turbocapitalist 01-10-2018 05:42 AM

Strange. sed should do the job. Which regex did you write? Or did you work with the 'a' command instead?

tiny.deluxe 01-10-2018 10:34 AM

I used
sed -e '0~5 commit;' test.sql > test1.sql

and in test1.sql where the same amount of lines as in test.sql but each fifth row was replaced by commit. :scratch:

Turbocapitalist 01-10-2018 10:37 AM

Ah. You missed the actual sed command: 'a'
Code:

sed -e '0~5 acommit;' test.sql > test1.sql
See 'man sed' for the details. You've also figured out how to increase the steps to 1000 or more, I presume?

MadeInGermany 01-11-2018 04:51 AM

Without the a (append) it becomes a c (change) followed by the string "ommit".


All times are GMT -5. The time now is 02:39 PM.