【发布时间】:2021-06-28 17:56:26
【问题描述】:
可能这是一个基本而简单的问题,但是我已经环顾了两天,我无法弄清楚解决它的方法。
给定以下两段工作代码:
#!/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”文件的行数相同,并且这些行的排序顺序与随后在每个子目录中生成的文件的顺序相同。
非常感谢任何帮助。
谢谢,
【问题讨论】:
-
for dir in ${i}/${j}的意义何在?你只循环一个目录。 -
你不需要把
do的正文放在{}里面 -
一般来说,将
>>outfile放在个人echo或printf的末尾是不好的形式。最好在外部范围内进行重定向,这样文件就不会一遍又一遍地打开和关闭。例如,您可以将>even_numbers.txt放在文件中的第一个done之后,以重定向整个for循环的标准输出,而您根本不需要>>even_numbers.txts。 -
even_numbers.txt里面只有一行。您用 TAB 分隔数字,而不是换行符。 -
另外,only
mkdir -p "$i/$j"并且没有任何单独的mkdir "$i"命令会更有效。请记住,运行外部命令会带来巨大的性能损失(与内置命令相比)——您正在执行fork()、execve(),然后进行链接/加载/等等。
标签: bash for-loop while-loop cut