【Shell案例】【wc记录单词长度、for循环和if、awk文本分析工具】7、打印字母数小于8的单词

描述
写一个 bash脚本以统计一个文本文件 nowcoder.txt中字母数小于8的单词。

 

示例:
假设 nowcoder.txt 内容如下:
how they are implemented and applied in computer 

你的脚本应当输出:
how
they
are
and
applied
in

说明:
不要担心你输出的空格以及换行的问题

方法1:for循环和if

$内执行语句&-lt表示小于&单括号if条件

#!/bin/bash
for i in `cat nowcoder.txt`
do
    if [ $(echo $i | wc -m) -lt 9 ]; then
        echo $i
    fi
done

``同{}

#!/bin/bash
for i in $(cat nowcoder.txt)
do
    if [[ ${#i} -lt 8 ]]; then
        echo -e "$i"
    fi
done

[[]]同()

#!/bin/bash
for i in $(cat nowcoder.txt)
do
    if (($(echo $i | wc -L)<8)); then
        echo -e "$i"
    fi
done

方法2:awk -F "分隔符" ‘{}’ 文件名【文本分析工具】

使用awk文本分析工具-F分隔符

#!/bin/bash
awk -F " " '{for(i=1;i<=NF;i++){
    if(length($i)<8) {
        print $i
    }
}}' nowcoder.txt
#-F表示-F fs or --field-separator fs
#指定输入文件分隔符,fs是一个字符串或者是一个正则表达式,如-F:。

 

posted @ 2022-05-01 22:36  哥们要飞  阅读(96)  评论(0)    收藏  举报