I already have a solution to my problem, but I'm looking to see if it can be made more succinct and faster. The problem: given a list, as shown below, extract the pathname for any file in a directory named '[Ss]ample' and return it's index into the list. The index is also in the data itself. Note that pathnames can contain spaces. I'm also trying to avoid non-POSIX syntax and tools.
#!/bin/sh
list=$(cat <<'_EOF_'
Leigh.Harts.Mysterious.Planet.S01E06.PDTV.XviD-FiHTV (28 files):
# Done Priority Get Size Name
0: 100% Normal Yes 8.4 MB Leigh.Harts.Mysterious.Planet.S01E06.PDTV.XviD-FiHTV/Sample/sample-leigh.harts.mysterious.planet.s01e06.pdtv.xvid-fihtv.avi
1: 100% Normal Yes 4.6 KB Leigh.Harts.Mysterious.Planet.S01E06.PDTV.XviD-FiHTV/leigh.harts.mysterious.planet.s01e06.pdtv.xvid-fihtv.nfo
26: 100% Normal Yes 9.4 MB Leigh.Harts.Mysterious.Planet.S01E06.PDTV.XviD-FiHTV/leigh.harts.mysterious.planet.s01e06.pdtv.xvid-fihtv.part25.rar
27: 100% Normal Yes 1.8 KB Leigh.Harts.Mysterious.Planet.S01E06.PDTV.XviD-FiHTV/leigh.harts.mysterious.planet.s01e06.pdtv.xvid-fihtv.sfv
_EOF_
)
index=-1
for file in $(
# The echo emulates the call to the external program.
echo "$list" | grep '^ *[0-9]\+:' | cut -c 35-
)
do
index=$((1 + $index))
case "$file" in
*/[Ss]ample/*)
# act upon this file
echo "do something with $index"
;;
esac
done
list='Leigh.Harts.Mysterious.Planet.S01E06.PDTV.XviD-FiHTV (28 files):
# Done Priority Get Size Name
0: 100% Normal Yes 8.4 MB Leigh.Harts.Mysterious.Planet.S01E06.PDTV.XviD-FiHTV/Sample/sample-leigh.harts.mysterious.planet.s01e06.pdtv.xvid-fihtv.avi
1: 100% Normal Yes 4.6 KB Leigh.Harts.Mysterious.Planet.S01E06.PDTV.XviD-FiHTV/leigh.harts.mysterious.planet.s01e06.pdtv.xvid-fihtv.nfo
26: 100% Normal Yes 9.4 MB Leigh.Harts.Mysterious.Planet.S01E06.PDTV.XviD-FiHTV/leigh.harts.mysterious.planet.s01e06.pdtv.xvid-fihtv.part25.rar
27: 100% Normal Yes 1.8 KB Leigh.Harts.Mysterious.Planet.S01E06.PDTV.XviD-FiHTV/leigh.harts.mysterious.planet.s01e06.pdtv.xvid-fihtv.sfv'
No need for grep or cut:
while read a b c d e file g
do
index=$((1 + $index))
case $file in
*/[Ss]ample/*)
# act upon this file
echo "do something with $index"
;;
esac
done <<.
$list
.