How to find incremental numbers in a file and increase them by a certain amount with perl and SEDMar 7th, 2014 | By admin | Category: Linux / Freebsd
So let’s say you have a file and in it is ton of field ID’s, something like this
<field id=”68″ size=”medium” type=”checkbox”>
What you want to do is take the first 68 of these fields as well as all of their code and then append these new 68 fields and all of their code onto your file as apposed to writing them all out by hand. Of course after doing this you are going to have to ensure that 100% of your fields in your code have a unique field ID and that is going to require going through to your pasted fields and manually adding 68 to them so that pasted field 1 becomes 69 and so on. Can’t have 2 fields with the same ID after all.
Well that’s all fine and dandy, chances are even by going through and doing this by hand you are still saving yourself a ton of time compared to recreating them all by hand however as any bash-head knows, there’s gotta be an easier way. For that we’re going to need to go in and user perl and SED. Unfortunately in my 5 minutes of googling and then 10 minutes of hacking I couldn’t figure out, in my limited knowledge, how to get perl to search for field id=”68″ and replace it with field id=”69″ I could only find out how to get it to replace it with an incrementally larger number. As such I had it search for id=”##” and replace it with ##+1 which means I had to use SED to go in and re-add the missing id=”##” to the file. Obviously there’s a way to do this all with perl but I hadn’t the time nor patience to figure out so please feel free to suggest a better solution but this is my solution
perl -pe ‘s/id=\”(\d+)\”/ $1+1 /ge’ yourfilename.txt | sed -e “s/field /field id=\”/g” | sed -e “s/ size=/\” size=/g”
This just adds 1 to the numbers but you will want to change that to correspond with the amount of id’s coming before your point of paste. So if you are putting your pasted code after ID #69 then $1+1 would become $1+69