Wednesday, July 23, 2014

Generic ls loop to perform action on specific files

lsdo.bsh:  
#!/usr/bin/env bash

function usage {
cat <<  EOF
Usage: lsdo [LSDIR: ls -tr directory] [FILTER: eg. "tail -8"] [DOCMD: eg. cp "EACH" .]
  Eg. lsdo
. "tail -5 | grep -i mp3" "stat EACH" 
EOF
}
 

LSDIR=${1:-"/tmp"}
FILTER=${2:-tail -8}
DOCMD=${3:-echo \"\$LSDIR/\$a\"}

[[ $# -eq 0 ]] && usage && exit 0
 

IFS=$(echo -en "\n\b") && for a in $(ls -tr "$LSDIR" | eval $FILTER); do eval $(echo "$DOCMD" | sed 's/EACH/\"\$LSDIR\/\$a\"/g');  done && unset IFS

$ lsdo.bsh . "tail -5"
./gawk_rev_sh.bsh
./mp42mp3.bsh
./grace_kill_win.bsh
./myaliases.bsh
./lsdo.bsh

 $ lsdo.bsh . "tail -5 | grep -i mp3"
./mp42mp3.bsh 

$ lsdo.bsh . "tail -5 | grep -i mp3" "stat EACH"  
 File: `./mp42mp3.bsh'
 Size: 1058          Blocks: 24         IO Block: 4096   regular file
Device: 19h/25d    Inode: 259872      Links: 1
Access: (0775/-rwxrwxr-x)  Uid: ( 1000/cronkilla)   Gid: ( 1000/cronkilla)
Access: 2014-07-22 20:26:29.880524398 -0400
Modify: 2014-07-10 17:32:52.207333868 -0400
Change: 2014-07-10 17:32:52.216333868 -0400
 Birth: -

No comments:

Post a Comment