编写 shell 脚本以打印具有某些参数的一定数量的行



我有 5 个变量,每个变量包含 5 个值。我想用五个变量中的五个值一一打印五行例如

$a=1 2 3 4 5
$b=4 2 3 4 5
$c=8 9 7 6 5
$d= 8 7 6 5 4
$e=5 6 7 3 3

我想以这种格式打印五行

My options was a=1,b=4,c=8,d=8and e=5
My  options was a=2,b=2,c=9,d=7 and e=6

依此类推,最多五个值。

我对使用循环感到困惑。谁能帮我在脚本中提供循环以获得以下输出。

a="1 2 3 4 5"
b="4 2 3 4 5"
c="8 9 7 6 5"
d="8 7 6 5 4"
e="5 6 7 3 3"
for i in $(seq 1 5); do
    echo -e "My options was c"
    echo -e "a=$(echo $a | cut -f$i -d' ')c"
    echo -e "b=$(echo $b | cut -f$i -d' ')c"
    echo -e "c=$(echo $c | cut -f$i -d' ')c"
    echo -e "d=$(echo $d | cut -f$i -d' ') and c"
    echo -e "e=$(echo $e | cut -f$i -d' ')"
done

将这个awk命令与 bash 循环一起使用:

for i in {1..5}; do
awk '{printf "My options was a=%d, b=%d, c=%d, d=%d and e=%dn", $1, $2, $3, $4, $5}' <<< $(awk '{print $'$i'}' <(echo -e "$an$bn$cn$dn$e") | tr $'n' ' '); done

输出:

$ a='1 2 3 4 5'
$ b='4 2 3 4 5'
$ c='8 9 7 6 5'
$ d='8 7 6 5 4'
$ e='5 6 7 3 3'
$ for i in {1..5}; do
awk '{printf "My options was a=%d, b=%d, c=%d, d=%d and e=%dn", $1, $2, $3, $4, $5}' <<< $(awk '{print $'$i'}' <(echo -e "$an$bn$cn$dn$e") | tr $'n' ' '); done
My options was a=1, b=4, c=8, d=8 and e=5
My options was a=2, b=2, c=9, d=7 and e=6
My options was a=3, b=3, c=7, d=6 and e=7
My options was a=4, b=4, c=6, d=5 and e=3
My options was a=5, b=5, c=5, d=4 and e=3

如果你转置矩阵,这真的很简单、可移植和惯用。

while read -r a b c d e; do
    : stuff with "$a", "$b", etc
done <<____
    1 4 8 8 5
    2 2 9 7 6
    3 3 7 6 7
    4 4 6 5 3
    5 5 5 4 3
____

请注意第一列如何枚举a值、第二如何枚举b s 等。

相关内容

  • 没有找到相关文章

最新更新