Parsing the output of ls
is a bad idea (the output of ls
is strictly for looking at). For more info on that, see the question "Why *not* parse `ls`?".
This is how you may do it under /bin/sh
:
for filename in t-*-*.c; do
[ ! -f "$filename" ] && continue
number=${filename#t-} # remove "t-" from start of filename
number=${number%%-*} # remove everything from first "-" in what remains
printf '%s\n' "$number"
done
This would iterate over all filenames in the current directory whose name matches the pattern t-*-*.c
. For each of these names, the t-
bit is stripped off from the start, and then the second -
and everything afterwards is removed with another parameter expansion.
The expansion ${variable#word}
would remove the (shortest) match for word
from the start of $variable
, while ${variable%%word}
would remove the (longest) match for word
from the end of the string.
With bash
, using regular expression matching on the filenames:
for filename in t-*-*.c; do
[ ! -f "$filename" ] && continue
if [[ "$filename" =~ ^t-([0-9]+)- ]]; then
printf '%s\n' "${BASH_REMATCH[1]}"
fi
done
This would match and capture the digits after t-
in each filename. The captured group of digits is available in ${BASH_REMATCH[1]}
after a successful match. The index 1
refers to the first capture group (parenthesis) in the regular expression.
For a slow, but possibly comfortable (as in "familiar") solution, you may want to call an external command to parse out the bit of the string that you're interested in:
for filename in t-*-*.c; do
[ ! -f "$filename" ] && continue
cut -d '-' -f 2 <<<"$filename"
done
This assumes bash
and that you're ok with calling cut
in a loop. This would be much slower than using operation built into the shell itself. The cut
command here is asked to return the second -
-delimited field from the string passed to it from bash
(using a "here-string" redirection).