英文:
How to copy one row from a text file at a time in a bash for loop?
问题
在以下的bash循环中:
for i in {0..40}; do
*随机代码* X -o file_{i}.dat
对于每个文件,我尝试将X替换为另一个文件中的一行,结果如下:
*随机代码* ROW1 -o file_0.dat
*随机代码* ROW2 -o file_1.dat
*随机代码* ROW3 -o file_2.dat
...等等
你知道如何实现吗?
英文:
In the following bash loop:
for i in {0..40}; do
*random code* X -o file_{i}.dat
for each file, I am trying to replace the X with a row from another file, resulting in the following output:
*random code* ROW1 -o file_0.dat
*random code* ROW2 -o file_1.dat
*random code* ROW3 -o file_2.dat
...et cetera
Do you know any way to do it?
答案1
得分: 1
这里有几种可能性:
选项 1
提前将另一个文件的所需行读入数组中,然后在循环中通过索引访问元素。例如:
declare -a my_array
mapfile -t -n 41 my_array < other_file
for i in {0..40}; do
do_something "${my_array[$i]}" -o file_"$i".dat
done
选项 2
在循环中按需从另一个文件中读取行。例如:
for i in {0..40}; do
read -r line
do_something "$line" -o file_"$i".dat
done < other_file
你可能需要加强其中一个选项,以处理另一个文件不包含足够行的情况。
英文:
There are many possibilities. Here are a couple of the more plausible ones:
Option 1
Read the wanted rows of the other file into an array in advance, then access the elements by index in the loop. For example:
declare -a my_array
mapfile -t -n 41 my_array < other_file
for i in {0..40}; do
do_something "${my_array[$i]}" -o file_"$i".dat
done
Option 2
Read lines from the other file on-demand as you progress through the loop. For example:
for i in {0..40}; do
read -r line
do_something "$line" -o file_"$i".dat
done < other_file
You probably want to beef up either one of those with appropriate behavior for the case where the other file doesn't contain enough lines.
答案2
得分: 0
#!/bin/bash
逐行读取文件,最多读取41行,并将每行存储在数组中
lc=0
while IFS='' read -r line || [[ -n "$line" ]] && [ $lc -le 40 ]; do
array+=("$line")
lc=$((lc+1))
done < "input.txt"
如果数组元素超过40个
if [ ${#array[@]} -gt 40 ]; then
for i in {0..40}; do
printf "随机代码 %s -o file_$i.dat\n" "${array[$i]}"
done
fi
英文:
It could be done like this
#!/bin/bash
#read file line by line to a max of 41 and store each line in an array
lc=0
while IFS='' read -r line || [[ -n "$line" ]] && [ $lc -le 40 ]; do
array+=("$line")
lc=$((lc+1))
done < "input.txt"
#if array is greater than 40
if [ ${#array[@]} -gt 40 ]; then
for i in {0..40}; do
printf "*random code* %s -o file_$i.dat\n" "${array[$i]}"
done
fi
答案3
得分: 0
要在bash循环中逐行复制文本文件的一行,您可以使用"read"命令来读取文件的每一行,然后使用循环来处理每一行。
#!/bin/bash
# 打开文件以供读取
exec 3< file.txt
# 循环遍历文件中的每一行
while read -u 3 line; do
# 对每一行执行操作,例如将其复制到另一个文件
echo "$line" >> new_file.txt
done
# 关闭文件
exec 3<&-
英文:
To copy one row from a text file at a time in a bash for loop, you can use the read command to read each line of the file and then use a loop to process each line.
#!/bin/bash
# Open the file for reading
exec 3< file.txt
# Loop through each line in the file
while read -u 3 line; do
# Do something with the line, for example, copy it to another file
echo "$line" >> new_file.txt
done
# Close the file
exec 3<&-
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论