循环使用多个输入源逐个配对

时间:2017-03-06 13:45:11

标签: bash loops

要求

两个文件:A和W。

需要将文件A的第一行与文件W的第一行配对;第二到第二,第三到第三...

示例:

>>> File A 
text1
text2
text3
text4
text5
text6
text7
text8
text9

>>> File W 
1
2
3
4
5
6
7
8
9

我做了什么:

#!/bin/sh

while read -r a <&3; do
   while read w<&4; do
       echo "add host name $a ipv4-address $w"
   done 4<W
done 3<A

但输出迭代A的第一行,其中所有行都来自W:

add host name text1 ipv4-address 1
add host name text1 ipv4-address 2
add host name text1 ipv4-address 3
add host name text1 ipv4-address 4
add host name text1 ipv4-address 5
add host name text1 ipv4-address 6
add host name text1 ipv4-address 7
add host name text1 ipv4-address 8
add host name text1 ipv4-address 9
add host name text2 ipv4-address 1
add host name text2 ipv4-address 2
add host name text2 ipv4-address 3
add host name text2 ipv4-address 4
add host name text2 ipv4-address 5
add host name text2 ipv4-address 6
add host name text2 ipv4-address 7
add host name text2 ipv4-address 8
add host name text2 ipv4-address 9
add host name text3 ipv4-address 1
add host name text3 ipv4-address 2
add host name text3 ipv4-address 3

我该怎么做?

2 个答案:

答案 0 :(得分:3)

试试这个 -

paste a b|awk '{print "add host name " $1 " ipv4-address " $2}'
add host name text1 ipv4-address 1
add host name text2 ipv4-address 2
add host name text3 ipv4-address 3
add host name text4 ipv4-address 4
add host name text5 ipv4-address 5
add host name text6 ipv4-address 6
add host name text7 ipv4-address 7
add host name text8 ipv4-address 8
add host name text9 ipv4-address 9

答案 1 :(得分:0)

您可以尝试以下操作:

file1=A
file2=W

while read -r line1 && read -r line2 <&3 ; do
  printf "add host name %s ipv4-address %s\n" "${line1}" "${line2}"
done <${file1} 3<${file2}

但是没有包含故障处理,也没有测试两个文件中正确的行数。