所以你知道这个对吧?:Read a file line by line assigning the value to a variable
在没有循环的情况下,你如何做到这一点呢?我的情况是,循环会导致错误和混乱。(如果你曾经尝试过并行),但我仍然需要逐行读取文件。
有没有什么不需要循环的方法?xargs
?awk
?parallel
发布于 2018-05-31 08:11:17
使用readarray
将整个文件读入数组变量。每一行都是一个数组元素。
readarray -t arrayname < filename
发布于 2018-05-31 08:18:59
这个问题对我来说真的没有多大意义,但你肯定可以做到:
{
read line_one <&3; # Read from the input file
echo "The first line is $line_one"
read line_two -u 3; # A different method to read
echo "The second line in $line_two"
...
} 3< input file
请注意,实际上没有必要从fd 3读取数据,但如果您的命令不是从与读取数据相同的输入读取数据,则会更安全。
但是,如果你真的处于“循环会导致错误和混乱”的情况下,那么你就会遇到一个问题,而这不是解决方案。
发布于 2018-05-31 11:14:25
FWIW,使用递归函数(好的,递归可能是一个循环...)。首先是一些测试材料:
$ seq 1 4 > file
然后是函数fun
$ fun() {
if read -r line <&5 # read from defined FD 5
then
echo process $line # process the lines here
fun # recursive function call
fi
}
呼唤fun
$ exec 5< file
$ fun
process 1
process 2
process 3
process 4
$ exec 5<&- # close the FD
https://stackoverflow.com/questions/50614876
复制相似问题