与fd嵌套同时读取循环 [英] Nested while read loops with fd

查看:42
本文介绍了与fd嵌套同时读取循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从嵌套循环中的两个不同输入读取数据,但没有成功.对于这个问题,我一直遵循的最佳答案,还查看了文件描述符页面高级Bash脚本指南中的内容.

I'm trying to read from two different inputs in nested loops without success. I've followed the best answer on this question and also took a look at the file descriptors page of the Advanced Bash-Scripting Guide.

#!/bin/bash
while read line <&3 ; do
    echo $line
    while read _line <&4 ; do
        echo $_line
    done 4< "sample-2.txt"
done 3< "sample-1.txt"

sample-1.txt的内容

Foo
Foo

sample-2.txt的内容

Bar
Bar

预期产量

Foo
Bar
Bar
Foo
Bar
Bar

我得到的输出

Foo
Bar

推荐答案

您的文本文件不以换行符结尾:

Your text files do not end with newlines:

$ printf 'Foo\nFoo' > sample-1.txt
$ printf 'Bar\nBar' > sample-2.txt
$ bash tmp.sh
Foo
Bar
$ printf '\n' >> sample-1.txt
$ printf '\n' >> sample-2.txt
$ bash tmp.sh
Foo
Bar
Bar
Foo
Bar
Bar

如果

read 到达文件末尾而没有看到换行符,则退出状态为非零.可以解决此问题,但是最好确保文本文件正确以换行符结尾.

read has a non-zero exit status if it reaches the end of the file without seeing a newline character. There's a hack to work around that, but it's better to ensure that your text files correctly end with a newline character.

# While either read is successful or line is set anyway
while read line <&3 || [[ $line ]]; do

这篇关于与fd嵌套同时读取循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆