Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed: insert a string after every N lines

Tags:

sed

I want to insert a string after every 30 lines in my large file. I'm using mini-sed, which doesn't support ~ (tilde) range operator. I'm looking for sed-only solution please.

like image 464
user868923 Avatar asked Jul 29 '11 07:07

user868923


People also ask

How do you insert a sed line after a pattern?

You have to use the “-i” option with the “sed” command to insert the new line permanently in the file if the matching pattern exists in the file.

How do you use sed multiple times?

You can tell sed to carry out multiple operations by just repeating -e (or -f if your script is in a file). sed -i -e 's/a/b/g' -e 's/b/d/g' file makes both changes in the single file named file , in-place.

How do you insert a new line character after a fixed number of characters in a file?

@JM88, Unix/Linux use the line-feed character ( \n ) for line breaks. Mac uses the carriage-return character for line breaks ( \r ), and Windows uses a combination of the two ( \r\n ) for line breaks.


1 Answers

This thread is another example of how to over complicate things. This should do it:

sed '0~30 s/$/string/g' < inputfile > outputfile 

Every 30 lines "string" is inserted at the end of the line. If you want a new line with the word "string" just use "\n string".

like image 78
Miguel Avatar answered Sep 30 '22 18:09

Miguel