Sunday 15 June 2014

perl - Insert String every n lines, while also resetting line counter at desired string -


I have to read a text file and every N lines need to insert a string, but whenever I come, String

Using the code, every 3 line repeats the working line:

sed '0 ~ 3 s / $ / \ nINSERT / g' & lt; INPUT / PATH / FILE_NAME.txt> OUTPUT / PATH / FILE_NAME.txt

I think when line = header ... I do not think so to restart the counter ... I did not Success has also tried to use a shell command.

Previous Input:

  1. Header line here 2. Dog 3. Cat 4. Fish 5. Pony 6. Horse 8. Birds 7. Header line here 8. Whale 9. Header line here 10. Shark 11. Lizard 12. Dolphin Expected Output:  
  1. Header line here 2. Dog 3. Cat 4. INSERT 5. Fish 6 pony 7. Horses 8. INSERT 9. Birds 10. Header Line Here 11. Whale 12. Header Line Here 13. Shark 14. Lizard 15. INSERT 16. Dolphin  

< Div class = "post-text" itemprop = "text">

Suppose you should have INSERT on every fourth row (value of n is taken as 4 )

Apply it very easily using awk

  awk '/ header / {flag = 1} Or it could be! (Flag ++% 4) {print "INSERT"} 1 ' 

What does this do?

  • / if the header matches the line header , then flag to 1 as

    li>
  • ! (Flag ++% 4) {print "INSE RT"} lower flag% 4 == 0 then print

  • 1 is always correct, takes the default task to print the entire record / line (another awk idiom)


$ Cat input header line here dog cat fish pony horse bird fish header line here whale header line here shark lizard dolphin $ awk '/ header / {Flag = 1}! (Flag ++% 4) {print "INSERT"} 1 'input header line here dog cat INSERT fish pony horse bird INSERT fish header line here whale header line here shark lizard INSERT dolphin

No comments:

Post a Comment