Search code examples
bashfor-loopwhile-loopcut

How to print a single line of an existing file within a nested for loop in bash?


Probably this is a basic and simple question, but I have been looking around for two days and I am not able to figure out the way of solving it.

Given the following two pieces of working code:

#!/bin/bash

# First, I need to generate all even numbers for a list of n integers, in this example n=12

for number in 258 256 233 230 212 245 210 229 340 345 110 125; do
    for ((counter = 2; counter <= ${number}; counter += 2)); do
        printf "$counter\t" >> Even_numbers.txt
    done
    printf "\n" >> Even_numbers.txt
done


# Then, I need to print each of these lines into a different file with a specific directory structure, 
# that looks like the following one:

for i in 01 02 03; do
    mkdir "${i}"
    for j in panel1 panel2 panel3 panel4; do
        {
        mkdir "${i}/${j}"
        for dir in ${i}/${j}; do
            printf "# TEXT AAAAA\n" > "${i}/${j}/File_${i}_${j}.par"
            printf "# TEXT BBBBB\n" >> "${i}/${j}/File_${i}_${j}.par"
            # I need to print here a single line of the "Even_numbers.txt" file
            # for each of the File_${i}_${j}.par files
            # The 12 lines in the Even_numbers.txt file and the 12 .par files
            # are in the same order.
            printf "# TEXT CCCCC\n" >> "${i}/${j}/File_${i}_${j}.par"
        done
        }
    done
done

I need to print a single line of the "Even_numbers.txt" file in each of the files that are generated in the second chunk of code. The problem is that no matter what I do, I get always the entire file content written to each output, instead of the line that I need. The "Even_numbers.txt" file has the same number of lines and these lines are sorted in the same order as the files that are generated afterwards in each subdirectory.

Any help is highly appreciated.

Thanks,


Solution

  • First, you can create all the directories at once:

    mkdir -p {01..03}/panel{1..4}
    

    To put one line in each file, redirect the loop input from Even_numbers.txt, and use read inside the loop to get one line at a time.

    for i in 01 02 03; do
        for j in panel1 panel2 panel3 panel4; do
            parfile="${i}/${j}/File_${i}_${j}.par"
            read number
            printf "# TEXT AAAAA\n# TEXT BBBBB\n%s\n# TEXT CCCCC\n" "$number" > "$parfile"
        done
    done < Even_numbers.txt