繁体   English   中英

2 while 循环读取文件内容

[英]2 while loop to read contents of a file

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

例如。 file1 = 内容“123.45.67.89” file2 = 内容“hostname.cco”

输出:123.45.67.89 主机名.cco

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

它实际上很简单,但它确实需要从多个文件描述符中读取。 本质上,您像往常一样设置读取循环,并将文件重定向到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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM