word contain a specific letter

An old (and quite portable) way to do it is using a case statement:

var="information"
case $var in
     *i*) echo "An 'i' was found in $var";;
     * )  echo "There is no 'i' in $var";;
esac

As a one line function:

a="information"   b="i"

one(){ case $a in (*${b}*) true;; (*) false;; esac; }

And used with:

if one; then 
    echo "Found %b in $a"; 
else
    echo "The character '$b' was not found in the string '$a'"
fi

Other valid ways to perform the same test are:

two(){ [[  $a ==   *"$b"*      ]] ; }   # Using a pattern match.
t33(){ [[  $a =~    "$b"       ]] ; }   # Extended Regex (ERE) match.
f44(){ [[  $a =~ ^.*"$b".*$    ]] ; }   # Using a ERE with limits.
f55(){ [[  ${a//[!"${b}"]}     ]] ; }   # Removing all non-matching chars.
six(){ [ ! "$a" = "${a%"$b"*}"  ] ; }   # Using char removal. 
s77(){ [[  $a =~ ^.*$          ]] ; }   # Testing if string is valid.

All functions work with valid strings.
The timing of each function for strings of 10, 100, 1000, …, 1000000 (1Million) characters is below:

        Number of characters in the string.
        10     100    1000    10000   100000  1000000
one  0.024m  0.036m  0.047m   0.207m   2.117m  25.363m
two  0.028m  0.030m  0.043m   0.179m   2.081m  25.337m
t33  0.044m  0.041m  0.053m   0.151m   1.757m  22.695m
f44  0.064m  0.075m  0.241m   1.864m  19.489m 198.488m
f55  0.055m  0.182m  5.275m 421.886m
six  0.043m  0.057m  0.297m  13.987m
s77  0.056m  0.061m  0.154m   1.201m  12.749m 134.774m

The number of characters is built by repeating a character.
The string to be tested is built with something similar to:

a="$1$(repeat "$2" 10**$k)$3"

The script is called as:

$ ./script start a ending 

The function f55 becomes very slow if the size of the string processed gets longer than (around) 1000 characters. The same happens to function six for strings longer than (around) 10000 (10k) characters.

Function two is the faster for short strings and t33 (regex) is the best for longer strings.

Functions t33 to s77 change running times if run as:

$ LANG=C ./script

All become faster.

It is interesting to note that functions f44 and s77 will report the error *output false) if the string tested is an invalid utf-8 string, like:

$'\x80abcde'

Exactly as grep (the base command for regex) does (in a utf-8 locale):

$ echo $'\x80abcde' | grep '^.*$'       # no output

$ (LANG=C; echo $'\x80abcde' | grep '^.*$') 
�abcde
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值