0
votes

I want to loop through a certain range of file lines in my home directory. E.g. I have 10 lines of files in my home directory and I want to loop through the 2nd to the 9th file line and print them to the terminal.

For example, my home directory:

/home/
--file1.txt
--file2.txt
   .
   .
--file9.txt
--file10.txt

I want to print the filenames: file2.txt all the way through to file9.txt

How can I do such thing?

4
Please, clarify: do you want to print file names or lines (what lines)?choroba
So the output you posted are coming from a file or a command?Raman Sailopal
What's wrong with echo file[2-9].txt?oguz ismail
By lines I mean the way that files appear in an ls -l. The output I want is the filenames in the directory that correspond to the 2-9 linesJohnBoy
The filenames I gave were for the sake of the example, the filenames can any valid filename.JohnBoy

4 Answers

1
votes

Yet another way:

ls -1|sed -n 2,9p

Note that the ls option above is 1, not l.

0
votes

First you could create an array as

for a in $(ls); do array[$i]=$a; i=$(($i+1)); done

and then reference the range desired as (for items 2 through 9)

echo ${array[@]:1:10}

There's probably a more elegant way to fill the array.

0
votes
#!/bin/bash
cnt=0                                                    # Initialise a variable cnt
for i in *;
do 
  cnt=$((cnt+1));                                        # Loop through each filename which is read in as a variable i and increment the cnt variable.
  if [[ "$cnt" == "2" || "$cnt" == "9" ]];
  then 
    echo $i;                                             # If the cnt variable is 2 or 9, print the filename
  fi;
done
0
votes

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