简体   繁体   English

如何在 Bash 中的一行中打印 for 循环的输出

[英]How to print output of a for loop in a single line in Bash

echo -n "input: "
while read line 
do 
   array=("${array[@]}" $line)
done
len=${#array[@]}

echo -n "Output:"
for (( n=0; n<=len; n++ ))
    do 
    echo "${array[n]}" | rev
done 

I want the reversed output to be in a single line.我希望反向输出在一行中。

无偿截图

Why aren't you using a reverse loop?你为什么不使用反向循环?

sep="" # no separator before first entry
for ((n=len; n>=0; n--))
do 
    printf "%s%s" "$sep" "${array[n]}"
    sep=" "
done
printf '\n'

Generally prefer printf over echo -n , though both would work here.通常更喜欢printf不是echo -n ,尽管两者都可以在这里工作。

Or if you just want the output to be reversed character by character;或者,如果您只想将输出逐个反转;

echo "${array[@]}" | rev

But then why do you need an array at all?但是为什么你需要一个数组呢?

read -r -p 'input: '
echo "$REPLY" | rev

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM