如何在 bash 的嵌套 for 循环中打印现有文件的单行?

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

大概这是一道基础简单的题,但是我找了两天也没有想出解决的方法。

给定以下两段工作代码:

#!/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

我需要在第二段代码中生成的每个文件中打印一行“Even_numbers.txt”文件。问题是无论我做什么,我总是将整个文件内容写入每个输出,而不是我需要的行。 “Even_numbers.txt”文件具有相同的行数,并且这些行的排序顺序与之后在每个子目录中生成的文件的顺序相同。

非常感谢任何帮助。

谢谢,

首先,您可以一次创建所有目录:

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

要在每个文件中放置一行,请重定向来自 Even_numbers.txt 的循环输入,并在循环内使用 read 一次获取一行。

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