linuxshell的一些记录

韵味老鸟 2024-09-08 15:50:56

linux shell的一些记录

一:shell 判断是否包含字母M

1. 使用 grep 命令str="Hello World"if echo "$str" | grep -q "M"; then echo "Contains M"else echo "Does not contain M"fi

grep -q 用于静默搜索,如果找到匹配项则返回 0 状态码。

2. 使用 case 语句str="Hello World"case "$str" in *M*) echo "Contains M";; *) echo "Does not contain M";;esac

case 语句会检查 $str 变量是否包含 M。

3. 使用正则表达式str="Hello World"if [[ "$str" =~ M ]]; then echo "Contains M"else echo "Does not contain M"fi

使用 =~ 操作符匹配正则表达式。

4. 使用字符串替换str="Hello World"if [ "${str//[^M]}" != "$str" ]; then echo "Contains M"else echo "Does not contain M"fi

使用 //[^M] 替换掉所有非 M 的字符,如果替换后的字符串与原字符串不同,则说明包含 M。

5. 使用 expr 命令str="Hello World"if echo "$str" | grep -o "M" | wc -l | grep -q "0"; then echo "Does not contain M"else echo "Contains M"fi

grep -o 只输出匹配的部分,wc -l 统计匹配行数,如果为 0 则说明不包含

0 阅读:0

韵味老鸟

简介:感谢大家的关注