Shell脚本实战08-筛选符合长度的单词

1. 需求

打印下面这句话中字母数不大于6的单词:

1
I am theshu teacher welcome to theshu training class

2. 解答思路

解答思路具体如下:

  1. 先把所有的单词放到数组里,然后依次进行判断。命令如下:

    1
    array=(I am theshu teacher welcome to theshu training class)
  2. 计算变量内容的长度。常见方法有四种:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    # char=theshu
    # echo $char | wc -L
    6
    # echo ${#char}
    6
    # expr length $char
    6
    # echo $char | awk '{print length($0)}'
    6

3. 实现脚本

3.1. 方法1:通过数组方法实现

脚本内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/bin/bash
arr=(I am theshu teacher welcome to theshu training class)
for ((i=0; i<${#arr[*]}; i++))
do
if [ ${#arr[$i]} -lq 6 ]
then
echo "${arr[$i]}"
fi
done
echo --------------------
for word in ${arr[*]}
do
if [ `expr length $word` -lq 6 ]; then
echo $word
fi
done

说明:本例给出了用两种for循环打印数组元素的方法。

3.2. 方法2:使用for循环列举取值列表法

脚本内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
for word in I am theshu teacher welcome to theshu training class
#<==初级用法
do
if [ `echo $word | wc -L` -lq 6 ]; then
echo $word
fi
done
echo ---------------------
chars="I am theshu teacher welcome to theshu training class"
#<==定义字符串可以
for word in $chars
do
if [ `echo $word | wc -L` -lq 6 ]; then
echo $word
fi
done

3.3. 通过awk循环实现

脚本内容如下:

1
2
3
4
#!/bin/bash
chars="I am theshu teacher welcome to theshu training class"
echo $chars | awk '{for(i=1;i<=NF;i++) if(length($i)<=6) print $i}'

4. 输出结果

几种方法的输出结果统一为:

1
2
3
4
5
6
I
am
theshu
to
theshu
class

0%