> shell编程 >

shell脚本:打印文本中字符数不大于6的单词

题目来源于老男孩空间日志,是一家企业面试题,题目如下:

for循环打印下面这句话中字母数不大于6的单词;
I am oldboy teacher welcome to oldboy traning class



方法1:

使用数组a,存放文本里的单词;for循环轮询,if判断每一个单词的长度,打印小于等于6的单词;

[root@localhost anglea]# cat 1.sh
#!/bin/bash
#written by mofansheng@2015-10-28
a=(I am oldboy teacher welcome to oldboy traning class)
for((i=0;i<${#a[*]};i++))
do
    if [ ${#a[$i]} -le 6 ]
      then
        echo ${a[$i]}
    fi
done


上面的if判断还可以使用expr length判断字符串长度;

[root@localhost anglea]# cat 1.sh
#!/bin/bash#written by mofansheng@2015-10-28
a=(I am oldboy teacher welcome to oldboy traning class)
for((i=0;i<${#a[*]};i++))
do
    if [ `expr length ${a[$i]}` -le 6 ]
    then
        echo ${a[$i]}
    fi
done


数组的另一种方法:直接读取数组里的元素,判断元素的长度;

arr=(I am oldboy teacher welcome to oldboy traning class)
for file in ${arr[@]}
do
    if [ ${#file} -le 6 ]
    then
        echo $file
    fi
done


执行结果如下:

[root@localhost anglea]# sh 1.sh
I
am
oldboy
to
oldboy
class


方法2:

使用for循环轮询单词,使用wc -L判断单词长度,并做判断;

[root@localhost anglea]# cat 2.sh
#!/bin/bash#written by mofansheng@2015-10-28
for f in I am oldboy teacher welcome to oldboy traning class
do
    [ `echo $f|wc -L` -le 6 ] && echo $f
done


执行结果如下:

[root@localhost anglea]# sh 2.sh
I
am
oldboy
to
oldboy
class


方法3:awk的length用法

[root@localhost anglea]# echo "I am oldboy teacher welcome to oldboy traning class"|awk '{for(i=1;i<=NF;i++) if(length($i)<=6) print $i}'
I
am
oldboy
to
oldboy
class



(责任编辑:IT)