test test
test test

Reputation: 87

Two variables in for loop in bash

for file in /root/*
do
    if [ "$file" != "/root/00" ] && [ "$file" != "/root/01" ]
    then
        echo $file
    fi
done

in this code, as you see i try to get the files in the /root folder the output should be like this:

/root/02
/root/03
/root/04
/root/05
etc....

then i will use the output with commands

i have txt file, let's say the content like this:

first line
second line
third line

i need read the txt file lines with the output from the code above in the same for loop, for example in the code echo $file i need change it to echo $file $line $line = the lines in the txt file

i found someone asked for something like my question and other in stackoverflow: https://www.unix.com/shell-programming-and-scripting/75414-sh-two-variables-loop.html

but all these, will not help me, because there are specific thing i need it!

what is the problem with their codes?

the problem is the out put will be like this:

the out put + the txt file

/root/02 first line
/root/03 second line
/root/04 third line
/root/05
/root/06

i need if the output lines more than the lines in the txt file return to the first line in the txt file for example:

/root/02 first line
/root/03 second line
/root/04 third line
/root/05 first line
/root/06 second line

Thanks.

Upvotes: 0

Views: 663

Answers (1)

Barmar
Barmar

Reputation: 780724

Put the lines of the file in an array. Then you can index the array with wraparound.

readarray -t lines < filename.txt
i=0
for file in /root/*
do
    if [ "$file" != "/root/00" ] && [ "$file" != "/root/01" ]
    then
        printf "%s %s\n" "$file" "${lines[$i]}"
        i=$(((i + 1) % "${#lines[@]}")) # increment i and wrap around to 0
    fi
done

Upvotes: 2

Related Questions