It's generally a bad idea to parse ls
output, because weird characters in filenames can cause hard-to-parse output -- use a wildcard (like *
) instead. In bash, it's easy to capture the result of a wildcard expansion to an array, and then you can iterate over the array (or a selected part of it). Here's an example getting files from the current working directory (not necessarily your home directory):
files=(*)
for file in "${files[@]:2:8}"; do # 8 items starting at #2 = #2 through #9
echo "$file" # or whatever
done
Now, if you want files from your home directory, you have to specify the path as part of the wildcard pattern, and the results you get will include that path (e.g. you'd get something like "/home/johnboy/file1.txt" instead of just "file1.txt"). If you want just the name, you have to remove the path part:
files=(~/*)
for file in "${files[@]:2:8}"; do
echo "${file##*/}" # the ##*/ modifier removes the path prefix
done
echo file[2-9].txt
? – oguz ismail