簡體   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