【发布时间】:2018-04-15 16:14:53
【问题描述】:
此脚本将 cvs 列表分成三列。 我们专注于“名称”列。我想找出字符最多的名字。一旦找到字符最多的名称,我想将其分配给一个变量。
#!/bin/bash
for i in $(cat homeaway.txt )
do
echo $i | while IFS=, read -r area name host
do
maxLength=0
length=${#name}
if [ $length -gt $maxLength ] ; then
maxLength=$length
else
:
fi
printf "%s\n" $maxLength
done
done
脚本说 - 英文 - 如果长度大于 maxlength,则将长度设置为 maxLength,如果不是,则不执行任何操作。 其中字符最多的区域字符串是“script_name_12345678999999”,共有 26 个字符。当脚本读取所有字符时,$maxLength 应该返回 26。
__DATA__
HOME,script_name_12345,USAhost.com
AWAY,script_name_123,USAhost.com
HOME,script_name_1,EUROhost.com
AWAY,script_name_123,USAhost.com
HOME,script_name_123456,EUROhost.com
AWAY,script_name_12345678999999,USAhost.com
HOME,script_name_1234,USAhost.com
AWAY,script_name_1234578,USAhost.com
HOME,script_name_12,EUROhost.com
AWAY,script_name_123456789,USAhost.com
一旦脚本达到包含 26 个字符的区域值,它应该停止将任何内容分配给 $maxLength。 相反,它返回每个字符串长度的列表,我不知道零是如何进入这里的
casper@casper01.com $ ./length_test.sh
17
0 ### how does the zero get in here ?
15
13
15
18
26 ###script_name_12345678999999
16
19
14
21
【问题讨论】:
-
maxLength=0每个循环? -
循环中的每次迭代都不打算让 maxLength 归零。我以为我只是在初始化它。
标签: bash list while-loop max