BASH脚本循环通过4个不同的文本文件

时间:2018-03-09 16:53:41

标签: bash shell scripting

我尝试创建一个BASH脚本,该脚本从四个不同的文本文件中获取数据,并将每个文本文件中的每一行分配给一个变量,然后使用这些变量运行命令。我已经构建了一个for循环来完成这项任务,但我遇到的挑战是for循环并不是在一个映射上进行。

我希望这个循环遍历每一行并且每行运行一次命令并在它到达EOF时停止循环。当我运行这个脚本时,我得到如下输出;

The username is jsmith The hostname is 0000-Ubuntu The description is P-Ubuntu The IP is 0.0.0.0/24

The username is jsmith The hostname is 0000-Ubuntu The description is P-Ubuntu The IP is 1.1.1.1/24

The username is jsmith The hostname is 0000-Ubuntu The description is P-Ubuntu The IP is 2.2.2.2/24

我需要这是一个一个映射;例如:

The username is jsmith The hostname is 0000-Ubuntu The description is P-Ubuntu The IP is 0.0.0.0/24

The username is pstone The hostname is 1111-Ubuntu The description is P-Ubuntu The IP is 1.1.1.1/24

The username is drogers The hostname is 3333-Ubuntu The description is P-Ubuntu The IP is 3.3.3.3/24

依旧......

正如您所知,我是bash脚本的新手,我非常感谢任何指导/帮助。

谢谢!

#!/bin/bash
HOSTNAMES=$(cat /home/squadri/hostnames.txt)
DESCRIPTIONS=$(cat /home/squadri/descriptions.txt)
USERNAMES=$(cat /home/squadri/usernames.txt)
IPS=$(cat /home/squadri/ips.txt)

for i in $HOSTNAMES ; do
for j in $DESCRIPTIONS ; do
for k in $USERNAMES ; do
for l in $IPS ; do
        echo "The username is $k"
        echo "The hostname is $i"
        echo "The description is $j"
        echo "The IP is $l"
            done
       done
     done
done

2 个答案:

答案 0 :(得分:0)

您可以使用paste命令:

paste /home/squadri/{hostnames,descriptions,usernames,ips}.txt |\
while read hostname description username ip; do
    echo "The username is $username"
    echo "The hostname is $hostname"
    echo "The description is $description"
    echo "The IP is $ip"
done

这种方法的一个潜在缺陷是文件中的空白字符,但如果文件中的任何一行都没有,那么它应该可以正常工作。

答案 1 :(得分:0)

从4个不同的文件描述符中读取:

while IFS= read -r hostname;
      IFS= read -r description <&3;
      IFS= read -r username <&4;
      IFS= read -r ip <&5; do
  echo "The username is $username"
  echo "The hostname is $hostname"
  echo "The description is $description"
  echo "The IP is $ip"
done < hostnames.txt 3< descriptions.txt 4< usernames.txt 5< ips.txt

从技术上讲,无论其他文件的长度如何,都会一直读到descriptions.txt的末尾。要在最短文件结束时停止,请使用&&

加入命令
while IFS= read -r hostname &&
      IFS= read -r description <&3 &&
      IFS= read -r username <&4 &&
      IFS= read -r ip <&5; do
  echo "The username is $username"
  echo "The hostname is $hostname"
  echo "The description is $description"
  echo "The IP is $ip"
done < hostnames.txt 3< descriptions.txt 4< usernames.txt 5< ips.txt

迭代直到你到达最长文件的末尾有点复杂(你不能简单地用||加入命令),所以我将它作为练习留给除非有要求,否则感兴趣的读者。