【问题标题】:2 while loop to read contents of a file2 while循环读取文件内容
【发布时间】:2018-02-20 09:40:10
【问题描述】:

我有 2 个文件。假设file1和file2。我想将 file1 和 file2 一起读取,这样它就会在一行中给我一个输出。

例如。文件 1 = 内容“123.45.67.89” file2 = 内容“hostname.cco”

输出:123.45.67.89 主机名.cco

我正在运行嵌套循环,但似乎无法完成我想做的事情。

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    这实际上很简单,但它确实需要从多个文件描述符中读取。本质上,您像往常一样设置了一个读取循环,并将一个文件重定向到fd3stdin 上的第二个文件,然后您可以在循环的每次迭代中从每个文件中读取独立的行。 (例如,从 file1 中读取 line1,从 file2 中读取 line1,等等)。您可以使用:

    #!/bin/bash
    
    while read -r -u 3 linea; do               ## reads linea from file1
        read -r lineb;                         ## reads lineb from file2
        printf "%s %s\n" "$linea" "$lineb"     ## outputs combined lines
    done 3<"$1" <"$2"  ## notice first file on fd3 and 2nd on stdin
    
    exit 0
    

    使用/输出示例

    然后使用file1file2 的文件内容,您将获得以下输出:

    $ bash read2fd.sh file1 file2
    123.45.67.89 hostname.cco
    

    如果这不是您想要的,请告诉我,我很乐意为您提供进一步的帮助。

    【讨论】:

      猜你喜欢
      • 2013-07-08
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 2012-01-24
      • 2022-01-21
      • 2014-04-18
      相关资源
      最近更新 更多