Every-n
From MairasNetWiki
Contents |
Introduction
Ever tried to perform an operation on every second file in a directory on the Linux command line. Surprising non-obvious. Since I needed to do such things repeatedly in the mapstitch project, I constructed this small script.
Examples
Copy every third file in a directory elsewhere.
cp `every 1/3 *` elsewhere
Rotate images 3 and 4 from every four images. For example, from the twelve images in a given directory, the bolded ones are rotated: 1 2 3 4 5 6 7 8 9 10 11 12.
for n in `every 3-4/4 cropped/s*.png`; do mogrify -rotate 180 $n done
Licence
The software is licenced under the X11 licence, which is a free and open-source licence, compatible with the GPL:
Copyright (C) 2007,2008 Matti Airas
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of the copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the copyright holders.
Source code
#! /usr/bin/env python from pyparsing import * import sys def parse(s): """ Define a grammar for parsing the argument strings, eg: 1/4 take every fourth item 2/4 take every fourth item, starting from the second 1,2/5 take items one and two out of every five 1-3/5 take items 1-3 out of every five """ slash = Literal("/").suppress() dash = Literal("-").suppress() item = Word(nums).setParseAction(lambda s,l,toks: int(toks[0])) itemrange = (item + dash + item).setParseAction( lambda s,l,toks: range(toks[0],toks[1]+1)) itemlist = Group(delimitedList(itemrange | item)) modulo = item clause = itemlist + slash + modulo res = clause.parseString(s) return res.asList() if __name__=='__main__': items, modulo = parse(sys.argv[1]) for i,s in enumerate(sys.argv[2:]): if i%modulo+1 in items: print s