Join 3,424 readers in helping fund MetaFilter (Hide)


Perl one-liner help
March 13, 2012 7:33 PM   Subscribe

Perl one-liner help - increment a number in a find-replace situation starting at a specific number?

Here's my one-liner:

perl -p -i -e 's/msdata:rowOrder=\"[0-9]*\"/"msdata:rowOrder=\"$1".(++$i)."\""/ge' file.xml

This finds all the rows in file.xml with the text msdata:rowOrder="18" and replaces the number in quotes incrementally throughout the file with 1, 2, 3, etc.,

How can I modify this so that I can specify the start number (i.e., start at 1000, then 1001, 1002, etc.,)
posted by odinsdream to Computers & Internet (8 answers total)
 
Why not just change (++$i) to (++$i+1000) or whatever your chosen offset is?
posted by introp at 7:39 PM on March 13, 2012 [2 favorites]


Perl has BEGIN and END blocks that you can use to accomplish this. You use them like this:
BEGIN { this_code_executed_once_at_the_beginning(); } this_code_executed_once_per_line; END { this_code_executed_once_at_the_end(); }
So, your oneliner would be come:
perl -p -i -e 'BEGIN{ $i = 1000} s/msdata:rowOrder=\"[0-9]*\"/"msdata:rowOrder=\"$1".(++$i)."\""/ge' file.xml
(On another note, did you know the -i option takes an argument which is the extension of a backup file? You can say
perl -i.bak 
and file.xml will get backed up as file.xml.bak)
posted by zrail at 7:43 PM on March 13, 2012 [1 favorite]


Because I've been doing data entry for like, eight hours straight, and have gotten maybe 4 hours of sleep a night for the past two weeks. That solved it, thank you!
posted by odinsdream at 7:43 PM on March 13, 2012


Try this:

perl -p -i -e '$i=1000; s/msdata:rowOrder=\"[0-9]*\"/"msdata:rowOrder=\"$1".($i++)."\""/ge' file.xml

In your original example, you haven't initialized $i, so it's just starting at 0. In my version, you specify its initial value. Notice that I also change the incrementing to post-increment, rather than pre-increment, so that your first number will be whatever you specify, rather than one more than what you specify.
posted by SomePerlGeek at 7:44 PM on March 13, 2012


SomePerlGeek Wouldn't that result in $i getting reset to 1000 on each run through the loop?
posted by zrail at 7:46 PM on March 13, 2012


SomePerlGeek; yeah, that resets it to all 1000 each time it finds.
posted by odinsdream at 7:54 PM on March 13, 2012


What I don't get is if you're specifically looking for 18, why the generalized regular expression?
posted by Obscure Reference at 6:19 AM on March 14, 2012


Sorry, 18 was a specific row example. That area is a dynamic repeating number throughout the file, with the same surrounding text.
posted by odinsdream at 8:54 AM on March 15, 2012


« Older Potty training question for th...   |  Somehow, my Ph.D. dissertation... Newer »
This thread is closed to new comments.