我有一个shell脚本,需要向用户询问4行输入。然后我需要显示输入的最长行,然后整个输入必须进入文件。 这就是我到目前为止所得到的:
#!/bin/bash
lines=()
echo "Please enter 4 lines of text: "
for ((i=1; i<=4; i++)); do
IFS= read -p "" -r line && lines+=("$line")
done
echo "The longest line you entered was: "
max=0
for((i=0;i<4;i++)); do
len=${#lines}
if [[ len -gt max ]] ; then
max=$len
long="${lines}"
fi
done
echo longest line="${long}" length="${max}"
echo "I'm now putting the four lines you entered into a text file called \"mylines.txt\"..."
printf "%s\n" "${lines[@]}" > lines.txt
这不是发生在我身上,你能告诉我我做错了什么吗? 感谢
答案 0 :(得分:3)
你可以在第一个循环中找出最长的行和长度:
#!/bin/bash
lines=()
max=0
echo "Please enter 4 lines of text: "
for ((i=1; i<=4; i++)); do
IFS= read -r line
lines+=("$line")
[[ ${#line} -gt $max ]] && { max=${#line}; long="$line"; }
done
echo longest line="${long}" length="${max}"
echo "I'm now putting the four lines you entered into a text file called \"mylines.txt\"..."
printf "%s\n" "${lines[@]}" > lines.txt
答案 1 :(得分:1)
使用您的确切示例,您只需要通过在设置len和long变量时指定索引$ i来实际遍历数组。
#!/bin/bash
lines=()
echo "Please enter 4 lines of text: "
for ((i=1; i<=4; i++)); do
IFS= read -p "" -r line && lines+=("$line")
done
echo "The longest line you entered was: "
max=0
for((i=0;i<4;i++)); do
#See how I added the [$i] this will allow you to get the length of each item in the array
len=${#lines[$i]}
if [[ len -gt max ]] ; then
max=$len
#This gets the item in the array to set the value of $long to it.
long="${lines[$i]}"
fi
done
echo longest line="${long}" length="${max}"
echo "I'm now putting the four lines you entered into a text file called \"mylines.txt\"..."
printf "%s\n" "${lines[@]}" > lines.txt
输出:
Please enter 4 lines of text:
one
two
three
four
The longest line you entered was:
longest line=three length=5
I'm now putting the four lines you entered into a text file called "mylines.txt"...