Friday, March 25, 2011

Printing a Specific Range With sed

Issue

You want to print only a specific range of lines from a file/input.

Solution

Use sed! Say for example you want to print out lines 15 through 30, you can do that like so:
sed -n '15,30p' [file]

Real World Scenario

Okay, so here's how I actually ended up using it; I have a process to publish files across hundreds of sites. I have a PHP script that prints out site information (one site per line). I also have another PHP script that handles publishing that takes in the site name as an argument. See where I'm going here? ;)

So what I need to do is loosely pseudo-coded as follows:

for site in siteinfo.php
publish.php $site

Where does the sed command come in handy? Well, like I said I have hundreds of sites to publish to, so a sleep comes in handy to give the servers a little break. So, I ended up breaking it up as follows:
for s in `/usr/local/bin/php sites.php|sed -n '1,100p'`; do /usr/local/bin/php publish.php $s; done | tee -a $log;
sleep 300;

for s in `/usr/local/bin/php sites.php|sed -n '101,200p'`; do /usr/local/bin/php publish.php $s; done | tee -a $log;
sleep 300;

etc...
etc...

No comments: