简体   繁体   English

2 while 循环读取文件内容

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

I have 2 file.我有 2 个文件。 Let's say file1 and file2.假设文件 1 和文件 2。 I want to read the file1 together with the file2 so it will give me an output into one single line.我想将文件 1 与文件 2 一起读取,这样它就会给我一个输出到一行中。

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

output: 123.45.67.89 hostname.cco输出:123.45.67.89 主机名.cco

Im runninng nested loop but seems I can not accoumplish what I want to do.我正在运行嵌套循环,但似乎我无法完成我想做的事情。

It's actually quite simple, but it does require reading from more than one file descriptor.它实际上很简单,但它确实需要从多个文件描述符中读取。 Essentially, you set up a read loop, as normal, and redirect a file to fd3 and a second file on stdin , you can then read independent lines from each file on each iteration of the loop.本质上,您像往常一样设置读取循环,并将文件重定向到fd3stdin上的第二个文件,然后您可以在循环的每次迭代中从每个文件中读取独立的行。 (eg read line1 from file1, line1 from file2, and so on). (例如从 file1 读取 line1,从 file2 读取 line1,等等)。 You can use:您可以使用:

#!/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

Example Use/Output示例使用/输出

Then using your file content for file1 and file2 , you would get the following output:然后将您的文件内容用于file1file2 ,您将获得以下输出:

$ bash read2fd.sh file1 file2
123.45.67.89 hostname.cco

If that is not what you intended, please let me know and I'm happy to help further.如果这不是您想要的,请告诉我,我很乐意为您提供进一步的帮助。

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

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