将循环变量输出与变量输入组合成一行

将循环变量输出与变量输入组合成一行
var1=( some command together )    

echo $var1
myserver [email protected] load24 /dev/tty  user1
myserver [email protected] load24 /dev/tty  user2
myserver [email protected] load24 /dev/tty  user3
myserver [email protected] load24 /dev/tty  user4

var2=$( some command together | awk '{print $5}')

echo "$var2"
user1
user2
user3
user4


for i in $var2;
do 
    ldapsearch -xyx $i
done;

循环的输出将类似于

DEP AB BC CD EF
dep GH IJ KL MN
DEP OP QR ST UV
DEP WX YZ AC BC

现在我想将所有变量组合起来看起来像

myserver [email protected] load24 /dev/tty  user1 EP AB BC CD EF
myserver [email protected] load24 /dev/tty  user2 dep GH IJ KL MN
myserver [email protected] load24 /dev/tty  user3 DEP OP QR ST UV
myserver [email protected] load24 /dev/tty  user4 DEP WX YZ AC BC

注意 - 我不想将任何输出重定向到任何临时文件,只想生成要写入的最后一个输出

答案1

我已经使示例独立于$var1$var2

#!/bin/bash

var1=$(for i in 1 2 3 4; do echo "a$i b$i  user$i"; done)
echo "$var1"

var2=$(for i in 1 2 3 4; do echo "user$i"; done)
echo "$var2"

for i in $var2
do
  j=$((j+1))
  line=$(echo "$var1" | head -n $j | tail -n 1)
  printf "%s  %s\n" "$line" "$(echo ldap result for $i)"
done

这输出:

a1 b1  user1
a2 b2  user2
a3 b3  user3
a4 b4  user4
user1
user2
user3
user4
a1 b1  user1  ldap result for user1
a2 b2  user2  ldap result for user2
a3 b3  user3  ldap result for user3
a4 b4  user4  ldap result for user4

在该printf行中,只需将echo ldap result for $i命令替换为您想要的命令,例如ldapsearch -xyx $i.

注意:使用 zsh(而不是 bash),由于它支持数组,这甚至可能更简单。

基于paste命令的替代解决方案(尽管间距不太可控):

#!/bin/bash

var1=$(for i in 1 2 3 4; do echo "a$i b$i  user$i"; done)
echo "$var1"

var2=$(for i in 1 2 3 4; do echo "user$i"; done)
echo "$var2"

for i in $var2
do
  echo "ldap result for $i"
done | paste <(echo "$var1") -

答案2

循环执行所有操作:

while read -r serv addr load tty usr; do
   printf "%s %s %s %s %s %s\n" \
      "${serv}" "${addr}" "${load}" "${tty}" "${usr}" $(ldapsearch -xyx "${usr}")
done < <( some command together )

< <( some command together )的输出重定向some command together到 while 循环中。

相关内容